2014-05-15 97 views
1

我正在使用代碼來獲取no。用於實現語義指向的特定詞組的命中。TypeError:'NoneType'對象在Python中沒有屬性'__getitem__'

def hits(word1,word2=""): 
query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s" 
if word2 == "": 
    results = urllib.urlopen(query % word1) 
else: 
    results = urllib.urlopen(query % word1+" "+"AROUND(10)"+" "+word2) 
json_res = json.loads(results.read()) 
google_hits=int(json_res['responseData']['cursor']['estimatedResultCount']) 
return google_hits 

,但是當我給包含的短語很長的文件,它執行高達一定程度,但返回錯誤

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

錯誤是動態的,因爲它有時會執行一些短語有時不是。我認爲它是我正在使用的谷歌API的問題。這個函數使用上面的計算SO。

def so(phrase): 
num = hits(phrase,"excellent") 
print num 
den = hits(phrase,"poor") 
print den 
ratio = (num/ den+0.01)*0.6403669724770642 
print ratio 
sop = log(ratio) 
return sop 

任何人有想法,請幫助!

+0

請張貼完整堆棧跟蹤。 – merlin2011

回答

1

你可以用下面的代碼複製錯誤:

None["key"] 

錯誤是告訴你的級別之一:

json_res['responseData']['cursor']['estimatedResultCount'] 

is None。您需要檢查您收到的數據是否符合您的期望。例如,作爲最小的變化:

try: 
    google_hits=int(json_res['responseData']['cursor']['estimatedResultCount']) 
except TypeError: 
    print query 
    print json_res 
    google_hits = 0 

此外,您的舊式%字符串格式化和+字符串連接的結構應與str.format取代:

query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={0}" 
payload = "{0} AROUND(10) {1}".format(word1, word2) if word2 else word1 
results = urllib.urlopen(query.format(payload)) 
+0

代碼真的很有用!但我又面臨同樣的問題,我認爲這是由於我使用的Google API。經過一定的否。的匹配返回了其阻止,並且不返回任何結果,並且它提供了錯誤消息[http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={0} {u'responseData' :沒有,請回復「詳細信息」:您認爲的濫用服務條款。請參閱http://code.google.com/apis/errors',u'responseStatus':403}] 如果有機會使用其他API來計算短語的HITS。如果有任何想法請幫助 – user3487858

相關問題