我正在尝试编写一个函数,允许我浏览 CSV 文件,然后解析该 CSV 文件,然后将每个值发送到 Google Search API(该位已写入)。
所以现在我有这个:
def loadtemplate():
filename = tkFileDialog.askopenfilename(filetypes = (("CSV files", "*.csv")
,("Text Files", "*.txt")
,("All files", "*.*") ))
if filename:
try:
csvfile = csv.reader(open(filename, 'rb'), delimiter=',')
for row in csvfile:
for x in row:
generate(x)
except:
tkMessageBox.showerror("Open Source File", "Failed to read file \n'%s'"%filename)
return
我的 CSV 文件如下所示:
seo,company name,drupal,wordpress themes,awesome web design
没有什么太疯狂了。无论如何,我收到了这个错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:/Python27/Projects/Google Searcher/realsearcher.py", line 20, in loadtemplate
generate(x)
File "C:/Python27/Projects/Google Searcher/realsearcher.py", line 31, in generate
gs = gs['cursor']
TypeError: 'NoneType' object is not subscriptable
似乎以某种方式将值设置为无?但是我一直尝试使用条件 where if x == None:
,它不允许查询通过,或者尝试将 CSV 文件更改为不应该解析类似内容的位置。
这是怎么回事,我该如何解决?
PS - 这是变量行的样子:
['seo', 'company name', 'drupal', 'wordpress themes', 'awesome web design']
这是 generate() (我使用了重复的代码,因为我觉得编写可以同时执行这两种解决方案的东西会花费更长的时间并且是不必要的,因为这个项目不会被扩展):
def generate(item):
infoget = urllib.quote(item)
infoquote = '"' + infoget + '"'
response = urllib2.urlopen("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + infoget)
gs = simplejson.load(response)
gs = gs['responseData']
gs = gs['cursor']
gs = gs['estimatedResultCount']
print gs
response = urllib2.urlopen("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + infoquote)
gs = simplejson.load(response)
gs = gs['responseData']
gs = gs['cursor']
gs = gs['estimatedResultCount']
print gs