【发布时间】:2016-07-14 22:15:37
【问题描述】:
这是我的代码。当我运行此代码时出现错误 引发异常 TypeError: 字符串索引必须是整数
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time
import MySQLdb
import simplejson
from HTMLParser import HTMLParser
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd='',
db='python',
charset='utf8',
use_unicode=True
)
cursor=db.cursor()
ckey = ''
csecret = ''
atoken = ''
asecret = ''
class listener(StreamListener):
def on_data(self, data):
all_data = simplejson.loads(HTMLParser().unescape(data))
#all_data = simplejson.loads(data)
# check to ensure there is text in
# the json data
if 'text' in all_data:
tweet = all_data["text"]
username = all_data["user"]["screen_name"]
我添加此语句以获取位置,但这不起作用
place= data['place']['full_name']
#location1= all_data["location"]
cursor.execute(
"INSERT INTO tweeter (time, username, tweet,location) VALUES (%s,%s,%s,%s)",
(time.time(), username, tweet,place))
db.commit()
print((username,tweet))
return True
else:
return True
这个 def on_status 函数是我在网上求助后添加的
def on_status(self, status):
if status.place:
print 'place:', status.place.full_name
return True
on_event = on_status
def on_error(self, status):
print(status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream (auth ,listener())
twitterStream.filter(track=["Earthquake"],languages = ["en"], stall_warnings = True )
请帮我解决我的问题。谢谢
【问题讨论】:
-
你知道错误是在哪一行抛出的吗?
-
我认为 place=data["place"]["fullname] def on_status(self, status): if status.place: print 'place:', status.place.full_name return True on_event = on_status