2014-05-15 96 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

相关问题