user3487858
user3487858

Reputation: 11

TypeError: 'NoneType' object has no attribute '__getitem__' in python

I am using a code for fetching no. of hits of a particular phrase for implementing Semantic Orientation.

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

but when I am giving a long file containing phrases it executes upto some extent but return Error

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

the error is dynamic as it sometimes executes some phrases and sometimes not. I think its a problem of google API which I am using. This function calculates SO using above .

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

Anyone has idea please help !!!

Upvotes: 1

Views: 2547

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122036

You can replicate the error with the following line of code:

None["key"]

The error is telling you that one of the levels of:

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

is None. You need to check that the data you receive is what you expect. For example, as a minimal change:

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

Also, your mix of old-style % string formatting and + string concatenation should be replaced with 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))

Upvotes: 1

Related Questions