-5

当我通过终端 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
4

1 回答 1

3

替换行:

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

经过

if ( len(result) and
    'responseData' in result and 
    'results' in result['responseData'] and      
    result['responseData']['results'] != []):
于 2013-04-18T14:26:33.977 回答