0

我正在尝试编写一个函数,允许我浏览 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
4

2 回答 2

5

从回溯中应该很明显,问题与 CSV 加载无关,而是来自generate函数。我们可以从该函数的代码中看到您正在查询 Google 搜索 API(针对每一行中的每个项目!)。但是,在各种情况下,您会得到一个空白结果。

您应该将函数重写为generate更明智,而不是向 Google 发送垃圾邮件(他们不喜欢它),并明智地处理故障 - 在依赖它们之前检查 JSON 中是否存在嵌套值。

于 2012-06-18T14:02:58.413 回答
1
gs = None
>>> gs = gs['aa']

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in -toplevel-
    gs = gs['aa']
TypeError: unsubscriptable object
>>> 

不知何故,变量 gs 被重新初始化或初始化为None

gs['responseData'] is None

尝试:

gs = simplejson.load(response)
gs = gs and gs ['responseData']
gs = gs and gs['cursor']
gs = gs and gs['estimatedResultCount']
print gs

例子:

gs = None
>>> gs and gs['aa']

>>> print gs
None
于 2012-06-18T13:56:15.097 回答