使用PythonNameError获取tweet
我是python的初学者。我想使用下面的代码来使用python获取推文使用PythonNameError获取tweet,python,twitter,Python,Twitter,我是python的初学者。我想使用下面的代码来使用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
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
但是在运行之后,我得到了以下错误
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
回溯(最近一次呼叫最后一次):
文件“E:\main project\python coding\sentisummarier\twitter reading\readingtest.py”,第23行,在
tweets=getData(“梅西”);
文件“E:\main project\python coding\sentisummarier\twitter reading\readingtest.py”,第19行,在getData中
自攻手错误(e)
NameError:未定义全局名称“self”
如何更正此错误?您正在模块级函数中使用
self
。只能在类实例方法中使用self
替换
self.handleError(e)
与
然后,您需要在模块中定义一个handleError
函数,类似于:
def handleError(error):
print error
这就解决了问题。我按照你说的修改了密码。但是现在我遇到了一个错误UnboundLocalError:Assignment之前引用的局部变量'tweets',您在
try.之后返回了tweets。。除了
块以及块内部。在try块之前初始化tweets变量(作为空列表),或者从函数末尾删除return tweets
def handleError(error):
print error