我是一个完全的编程菜鸟,正在尝试配置 Twitter-Tweepy-MySQL 收集机制。我已经回顾了很多关于此的类似帖子,但我无法完全得到答案,所以我希望我没有在这里重复......
我对运行的基本脚本感到满意,现在我正在尝试改进它以构建我想要的确切架构。
我花了几个令人沮丧的小时来尝试解决主题标签提取问题。我可以提取主题标签 - 问题是一条推文通常有六个,而我需要它们全部。我的问题是它们是 Tweet 对象中数组的一部分,我不太清楚如何告诉 Python 将它们全部提取并填充 MySQL。我很确定我需要使用其中一个条件,但无法使 TRY 或 IF 在每个主题标签行上工作...
当您看到下面我的脚本时,请尽量不要笑 - 我知道它非常业余,但 YouTube 只能带您到目前为止。我希望我想要做的事情是显而易见的,并且我将留下评论以展示我之前的一些尝试/想法。
非常感谢您的建议!罗宾
脚本如下:
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import MySQLdb
import time
import json
conn = MySQLdb.connect("snarf","snarf","snarf","snarf", charset='utf8')
c = conn.cursor()
#consumer key, consumer secret, access token, access secret.
ckey = 'snarf'
csecret = 'snarf'
atoken = 'snarf'
asecret = 'snarf'
class listener(StreamListener):
def on_data(self, data):
try:
tweet = json.loads(data)
screen_name = tweet["user"]["screen_name"]
created_at = tweet ["created_at"]
identity = tweet ["id"]
text = tweet ["text"]
hashtag1 = tweet ["entities"]["hashtags"][0]["text"]
#hashtag2 = tweet ["entities"]["hashtags"][1]["text"]
#hashtag3 = tweet ["entities"]["hashtags"][2]["text"]
#hashtag4 = tweet ["entities"]["hashtags"][3]["text"]
#hashtag5 = tweet ["entities"]["hashtags"][4]["text"]
#URL1 = tweet ["entities"]["urls"][0]["expanded_url"]
#URL2 = tweet ["entities"]["urls"][1]["expanded_url"]
#URL3 = tweet ["entities"]["urls"][2]["expanded_url"]
#URL4 = tweet ["entities"]["urls"][3]["expanded_url"]
#URL5 = tweet ["entities"]["urls"][4]["expanded_url"]
c.execute("INSERT INTO news (timestamp, screen_name, created_at, id, text, hashtag_1) VALUES (%s,%s,%s,%s,%s,%s)",
(time.time(), screen_name, created_at, identity, text, hashtag1))
conn.commit()
print((text))
return True
except BaseException, e:
print 'failed on data,',str(e)
time.sleep(5)
def on_error(self, status):
print status
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["#football", "#soccer"])
最佳答案
您可以像这样使用 for
循环:
hashtags = [] #make an empty list
for hashtag in tweet["entities"]["hashtags"]: #iterate over the list
hashtags.append(hashtag["text"]) #append each hashtag to 'hashtags'
c.execute("INSERT INTO news (timestamp, screen_name, created_at, id, text, hashtag_1) VALUES (%s,%s,%s,%s,%s,%s)", (time.time(), screen_name, created_at, identity, text, str(hashtags)))
它只是遍历主题标签列表并将文本附加到名为“主题标签”的列表中。因为我不知道有什么方法可以在 SQL 数据库中存储未定义长度的列表,所以我基本上使用 str()
将列表转换(序列化)为字符串,并将其存储在 hashtag_1 列中。
如果您正在寻找更详细的Python类(class):我真的很喜欢codecademy
编辑:
如果推文包含单引号,则仅部分保存文本。随后,您应该将以下代码放在 for 循环前面:
#I presume your tweet is saved in the variable text
txt = []
if "'" in text:
for item in text:
if not item=="'":
txt.append(item)
else:
txt.append("''")
text = ''.join(txt)
关于python - 使用 Tweepy 提取主题标签进入 MySQLdb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34514768/