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

Cec*_*uez 0 python csv exception

我正在尝试编写一个函数,允许我浏览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
Run Code Online (Sandbox Code Playgroud)

我的CSV文件如下所示:

seo,company name,drupal,wordpress themes,awesome web design
Run Code Online (Sandbox Code Playgroud)

没什么太疯狂的.无论如何,我收到这个错误:

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
Run Code Online (Sandbox Code Playgroud)

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

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

PS - 这是变量行的样子:

['seo', 'company name', 'drupal', 'wordpress themes', 'awesome web design']
Run Code Online (Sandbox Code Playgroud)

这是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
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 5

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

您应该重写该generate功能,使其更加明智,不要向Google发送垃圾邮件(他们不喜欢它),并合理地处理故障 - 在依赖它们之前检查嵌套值是否存在于JSON中.