我正在使用Python尝试在csv文件中存储与特定关键字相关的推文(更准确地说只是他们的日期,用户,生物和文本)。当我正在研究Twitter的免费API时,我每15分钟限制一次。所以我编写了一些应该在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)
您应该使用Python的CSV库来编写CSV文件。它需要一个包含行的所有项目的列表,并自动为您添加分隔符。如果某个值包含逗号,它会自动为您添加引号(这就是CSV文件的工作方式)。它甚至可以处理值内的换行符。如果您将结果文件打开到电子表格应用程序中,您将看到它已被正确读入。
而不是尝试使用time.sleep()
,更好的方法是使用绝对时间。因此,我们的想法是花费你的开始时间并增加三个小时。然后你可以继续循环,直到达到这个finish_time
。
可以对API调用分配采用相同的方法。保持一个计数器,保持你剩下的电话数和向下计数。如果它到达0
然后停止拨打电话,直到达到下一个十五分钟的时段。
timedelta()
可用于向现有的datetime
对象添加分钟或小时。通过这种方式,您的时间永远不会失去同步。
以下显示了如何使工作正常的模拟。您只需添加代码即可获取推文:
from datetime import datetime, timedelta
import time
import csv
import random # just for simulating a random ID
fifteen = timedelta(minutes=15)
finish_time = datetime.now() + timedelta(hours=3)
calls_allowed = 450
calls_remaining = calls_allowed
now = datetime.now()
next_allocation = now + fifteen
todays_date = now.strftime("%d_%m_%Y")
ids_seen = set()
with open(f'tweets_{todays_date}.csv', 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
while now < finish_time:
time.sleep(2)
now = datetime.now()
if now >= next_allocation:
next_allocation += fifteen
calls_remaining = calls_allowed
print("New call allocation")
if calls_remaining:
calls_remaining -= 1
print(f"Get tweets - {calls_remaining} calls remaining")
# Simulate a tweet response
id = random.choice(["1111", "2222", "3333", "4444"]) # pick a random ID
date = "01.01.2019"
user = "Fred"
bio = "I am Fred"
text = "Hello, this is a tweet\nusing a comma and a newline."
if id not in ids_seen:
csv_output.writerow([id, date, user, bio, text])
ids_seen.add(id)
至于继续写相同的推文的问题。您可以使用set()
来保存您编写的所有ID。然后,您可以在再次编写之前测试是否已经看到新的推文。