【发布时间】:2019-07-29 13:37:49
【问题描述】:
我正在使用 Python 尝试在 csv 文件中存储与特定关键字相关的推文(更准确地说是它们的日期、用户、简历和文本)。 由于我正在开发 Twitter 的免费 API,我每 15 分钟只能发布 450 条推文。 所以我编写了一些代码,它应该在 15 分钟内准确存储 450 条推文。
但问题是在提取推文时出了点问题因此在特定点上,相同的推文被一次又一次地存储。
任何帮助将不胜感激! 提前致谢
import time
from twython import Twython, TwythonError, TwythonStreamer
twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET)
sfile = "tweets_" + keyword + todays_date + ".csv"
id_list = [last_id]
count = 0
while count < 3*60*60*2: #we set the loop to run for 3hours
# tweet extract method with the last list item as the max_id
print("new crawl, max_id:", id_list[-1])
tweets = twitter.search(q=keyword, count=2, max_id=id_list[-1])["statuses"]
time.sleep(2) ## 2 seconds rest between api calls (450 allowed within 15min window)
for status in tweets:
id_list.append(status["id"]) ## append tweet id's
if status==tweets[0]:
continue
if status==tweets[1]:
date = status["created_at"].encode('utf-8')
user = status["user"]["screen_name"].encode('utf-8')
bio = status["user"]["description"].encode('utf-8')
text = status["text"].encode('utf-8')
with open(sfile,'a') as sf:
sf.write(str(status["id"])+ "|||" + str(date) + "|||" + str(user) + "|||" + str(bio) + "|||" + str(text) + "\n")
count += 1
print(count)
print(date, text)
【问题讨论】:
-
我建议您为 CSV 文件使用标准的逗号分隔符。如果您的推文包含逗号,则该字段通常用引号括起来。它还能够处理换行符。 Python 的 CSV 库会自动为您处理所有这些。
标签: python csv datetime twitter twython