【问题标题】:problem while storing tweets into csv file将推文存储到 csv 文件时出现问题
【发布时间】: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


【解决方案1】:

您应该使用 Python 的 CSV 库来编写您的 CSV 文件。它需要一个包含一行所有项目的列表,并自动为您添加分隔符。如果一个值包含逗号,它会自动为您添加引号(这就是 CSV 文件的工作方式)。它甚至可以处理值内的换行符。如果您将生成的文件打开到电子表格应用程序中,您将看到它已正确读取。

与其尝试使用time.sleep(),更好的方法是使用绝对时间。所以这个想法是把你的开始时间增加三个小时。然后,您可以继续循环,直到到达此 finish_time

您的 API 调用分配也可以采用相同的方法。保留一个计数器来记录您还剩下多少电话并减少它。如果它到达0,则停止拨打电话,直到到达下一个 15 分钟时隙。

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。然后,您可以在再次编写之前测试一条新推文是否已经被看到。

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2016-08-22
    • 2019-05-25
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多