from __future__ import division
import urllib,urllib2
import urllib
import json
from math import log
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
def so(phrase):
num = hits(phrase,"excellent") * hits("poor")
den = hits(phrase,"poor") * hits("excellent")
ratio = num / den
sop = log(ratio,2)
return sop
print so("beautiful product")
我需要上面的代码来计算给定短语(或字符串)的语义方向。
当我执行代码时,出现以下错误:
Traceback (most recent call last):
File "C:\Python27\nltkexp\ddddd.py", line 32, in <module>
print so("beautiful product")
File "C:\Python27\nltkexp\ddddd.py", line 24, in so
den = hits(phrase,"poor") * hits("excellent")
File "C:\Python27\nltkexp\ddddd.py", line 16, in hits
google_hits=int(json_res['responseData']['cursor']['estimatedResultCount'])
TypeError: 'NoneType' object has no attribute '__getitem__'
如何解决此错误?有人可以指出我的代码出错吗?
答案 0 :(得分:3)
您正在访问json_res['responseData']['cursor']['estimatedResultCount']
,问题是
json_res
或json_res['responseData']
或json_res['responseData']['cursor']
可能为None
,且无法访问key
对象的NoneType
。
请打印json_resp
并检查其中可用的密钥。