如何解决TypeError?

时间:2014-03-04 06:46:21

标签: python

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

如何解决此错误?有人可以指出我的代码出错吗?

1 个答案:

答案 0 :(得分:3)

您正在访问json_res['responseData']['cursor']['estimatedResultCount'],问题是

json_resjson_res['responseData']json_res['responseData']['cursor']可能为None,且无法访问key对象的NoneType

请打印json_resp并检查其中可用的密钥。

相关问题