我一直得到" NoneType对象不可订阅"

时间:2012-06-18 13:51:15

标签: python exception csv

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

似乎某种方式将值设置为None?但我继续尝试使用条件if x == None:,它不允许查询通过或尝试将CS​​V文件更改为应该解析的任何内容。

这里发生了什么,我该如何解决?

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

2 个答案:

答案 0 :(得分:5)

从追溯中可以明显看出,问题与CSV加载没有任何关系,而是来自generate函数。我们可以从该功能的代码中看到您正在查询Google Search API(对于每一行中的每个项目!)。但是,在各种情况下,您将得到一个空白的结果。

你应该重写generate函数,使其更加明智,不要向谷歌发送垃圾邮件(他们不喜欢它),并明智地处理失败 - 在依赖之前检查嵌套值是否存在于JSON中在他们。

答案 1 :(得分: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