getting tweets using python NameError

95 views Asked by At

I'm a starter in python.I want to use the following code to get tweets using python.

import urllib
import urllib2
import json


def getData(keyword):
    url = 'http://search.twitter.com/search.json'
    data = {'q': keyword, 'lang': 'en', 'result_type': 'recent'}
    params = urllib.urlencode(data)
    try:
        req = urllib2.Request(url, params)
        response = urllib2.urlopen(req)
        jsonData = json.load(response)
        tweets = []
        for item in jsonData['results']:
            tweets.append(item['text'])
        return tweets
    except urllib2.URLError, e:
        self.handleError(e)
    return tweets


tweets = getData("messi")

print tweets

but after running i get the following error.

Traceback (most recent call last):
  File "E:\main project\python coding\sentisummarizer\twitter-reading\readingtest.py",      line 23, in <module>
    tweets = getData("messi");
  File "E:\main project\python coding\sentisummarizer\twitter-reading\readingtest.py",     line 19, in getData
    self.handleError(e)
NameError: global name 'self' is not defined

how can i correct this error?

1

There are 1 answers

2
Mark Unsworth On BEST ANSWER

You are using self in a module level function. You should only use self inside a class instance method.

Replace

self.handleError(e)

with

handleError(e)

and then you need to define a handleError function in your module, something like:

def handleError(error):
  print error