Python:TypeError:'NoneType'对象没有属性'__getitem__'

时间:2013-04-18 14:20:43

标签: python python-2.7

当我通过终端m运行我的python代码时出现此错误:

def GPlag(text,encode=False):
        import urllib, urllib2, json

        if encode == True:
            text = text.encode('utf-8')

        query = urllib.quote_plus(text)
        base_url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='
        url = base_url + '%22' + query + '%22'
        request = urllib2.Request(url,None)
        response = urllib2.urlopen(request)
        result = json.load(response)
        output = []

        if result['responseData']['results'] != []:
            firstMatch = result['responseData']['results'][0]
            output.append(firstMatch['title'])
            output.append(firstMatch['visibleUrl'])
            output.append(firstMatch['content'])

        return output

        def callGPlag(n):
            for s in n:
                outcome = GPlag(s,encode=True)

它给出了;

TypeError: 'NoneType' object has no attribute '__getitem__'

在此if result['responseData']['results']行中。这是追溯:

Traceback (most recent call last): 
 ... in <module> GPlagFile(sys.argv[1]) 
 ... in GPlagFile outcome = GPlag(s,encode=True) 
 ... in GPlag if 'results' in result['responseData']: 
TypeError: argument of type 'NoneType' is not iterable

1 个答案:

答案 0 :(得分:3)

替换行:

if result['responseData']['results'] != []:

通过

if ( len(result) and
    'responseData' in result and 
    'results' in result['responseData'] and      
    result['responseData']['results'] != []):