这是我的代码。当我运行此代码时,我得到一个错误
提出例外
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 )
请帮助我解决我的问题。谢谢
最佳答案
在此之前,您必须在MySQL中创建一个表:
CREATE TABLE tweeter (time DATE,username VARCHAR(20),tweet VARCHAR(200),location VARCHAR(100));
然后运行脚本:
import tweepy
import MySQLdb
conn = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd='',
db='python',
charset='utf8',
use_unicode=True
)
x = conn.cursor()
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, api):
self.api = api
super(tweepy.StreamListener, self).__init__()
def on_status(self, status):
print status.text,'\n'
print status.user.screen_name, "\n"
print status.created_at, "\n"
if status.place:
print status.place.full_name
x.execute(
"INSERT INTO tweeter (time, username, tweet,location) VALUES (%s,%s,%s,%s)",
(status.created_at, status.user.screen_name, status.text,status.place.full_name))
conn.commit()
else:
x.execute(
"INSERT INTO tweeter (time, username, tweet,location) VALUES (%s,%s,%s,%s)",
(status.created_at, status.user.screen_name, status.text,"None"))
conn.commit()
def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True
sapi = tweepy.streaming.Stream(auth, CustomStreamListener(api))
sapi.filter(track=["earthquake"])