【问题标题】:TypeError: 'NoneType' object has no attribute '__getitem__' in pythonTypeError:'NoneType'对象在python中没有属性'__getitem__'
【发布时间】:2014-07-03 11:45:41
【问题描述】:

我正在使用代码来获取号码。实现语义定位的特定短语的命中数。

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__' "

错误是动态的,因为它有时会执行一些短语,有时不会。我认为这是我正在使用的 google 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

谁有想法请帮忙!!!

【问题讨论】:

  • 请发布完整的堆栈跟踪。

标签: python-2.7 typeerror


【解决方案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))

【讨论】:

  • 代码真的好用啊兄弟!!!但我再次面临同样的问题,我认为这是由于我使用的 Google API。一定没有后。的点击返回其被阻止且不返回任何结果,并给出错误消息 [ajax.googleapis.com/ajax/services/search/web?v=1.0&q={0} {u'responseData': None, u'responseDetails': u'Suspected of Service Terms Abuse。请参阅code.google.com/apis/errors', u'responseStatus': 403}] 如果有机会使用其他 API 来计算短语的 HITS。如果有任何想法请帮忙
猜你喜欢
  • 2018-04-13
  • 2013-04-15
  • 1970-01-01
  • 2017-01-08
  • 2017-08-17
  • 2012-12-04
  • 1970-01-01
  • 2014-08-14
相关资源
最近更新 更多