【问题标题】:Tweepy, how to correctly format output to csv file?Tweepy,如何正确格式化输出到 csv 文件?
【发布时间】:2020-07-25 17:26:32
【问题描述】:

我正在尝试使用一些关键字搜索 twitter 以查找特定日期的带有关键字的推文并将推文写入 csv 文件。


import pandas as pd
import tweepy as tw
import datetime

consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth,wait_on_rate_limit=True)


search_words = ["chelsea","liverpool"]
date_since = "2020-07-19"

startDate = datetime.datetime(2020,7,22,0,0,0)
endDate = datetime.datetime(2020,7,23,0,0,0)

# Collect tweets
for i in search_words:
    new_search = i + " -filter:retweets"
    tweets = tw.Cursor(api.search,
                  q=new_search, 
                  lang="en",
                  since=date_since,tweet_mode="extended").items(1000)


    # Iterate and print tweets
    for tweet in tweets:
        if tweet.created_at < endDate and tweet.created_at > startDate:  
            dfObj = dfObj.append({"Tweets": tweet.full_text},ignore_index=True)

dfObj.to_csv(r'tweet.csv',header=True)

csv 文件包含如下字符:

 🥴🥴 â€

如何去掉这些字符或在 csv 中正确输入?

还有什么方法可以在不循环列表的情况下搜索多个关键字?例如搜索任何包含短语“chelsea”或“liverpool”的推文?

【问题讨论】:

    标签: python csv tweepy


    【解决方案1】:

    您可以尝试使用以下代码更改最后一个代码块:

    with open("tweets.csv", "w") as f:
        writer = csv.writer(f)
        for tweet in tweets:
            if tweet.created_at < endDate and tweet.created_at > startDate:
                f.write("%s\n"% (tweet.full_text.encode("utf-8")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2020-02-22
      • 2020-06-14
      相关资源
      最近更新 更多