當我通過終端米運行我Python代碼收到這個錯誤:的Python:類型錯誤:「NoneType」對象沒有屬性「__getitem__」
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
檢查它的長度,而不是和/或如果' 'results''是'結果[' responseData 「]'。 – 2013-04-18 14:22:23
@Allendar你能告訴我爲什麼我得到這個錯誤嗎? 以及如何找到它的長度? – Razer
如果result'['responseData']:'和其中的另一個檢查'if'result'result(result ['responseData'] ['result'])> 0'。或類似的東西。你現在的問題是沒有什麼,因此'NoneType'。 – 2013-04-18 14:25:47