1

I'm a starter in python.I use the following code to get tweets depending on a input query.

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 tweet

but i get the following error in the above code. Name Error: global name 'self' is not defined. How can i correct this error?

3
  • 1
    I'm guessing you found this function online and that it was part of a class. You could remove the self. and write a function called handleError to deal with the problem. Commented Jan 31, 2014 at 4:55
  • you should look at the twitter package, its on pip. Commented Jan 31, 2014 at 5:14
  • This won't work at all, because the REST API v1 is deprecated. You need to authenticate via OAuth --> Have a look at one of the Twitter-Packages, if you do not want to deal with the whole OAuth process by yourself Commented Jan 31, 2014 at 8:35

1 Answer 1

1

Like ChrisP said, first you need to remove self. from your code. then you might get another error as handleError function is not defined anywhere in your code. So, You have to define the handleError function as well if you have not defined it yet.

Take a look at the python doc to learn more about classes and objects.

import urllib
import urllib2
import json

#defining handleError
def handleError(e):
    #Error Handling code goes here

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:
        handleError(e) #removed self.
    return tweets
tweets = getData("messi")
print tweet
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.