【问题标题】:How to Get Full Tweets in CSV Cells Using Tweepy.Cursor如何使用 Tweepy.Cursor 在 CSV 单元格中获取完整的推文
【发布时间】:2021-02-04 17:05:07
【问题描述】:

我对编码比较陌生(仅使用 R 进行回归建模),现在正在学习 Python 以获得研究助理。我目前的任务是使用 for 循环和 tweepy.Cursor/API 搜索通过主题标签列表搜索推文,并将它们转换为数据框并将结果存储在 CSV 文件中。

我已经设法做到了,但是在使用此代码后,推文在 CSV 文件的单元格中出现了截断(主要是从研究生那里继承来帮助我入门):

import tweepy as tw 
import pandas as pd
import numpy as np
import re

consumer_key = ""
consumer_secret = ""
atoken = ""
asecret = ""

auth = tw.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(atoken, asecret)
api = tw.API(auth, wait_on_rate_limit=True)

hashtag_list = open('hashtag_list.txt', "r")

tweets = []
appended_data = []
tw_all_hashtags = pd.DataFrame(columns = ["text", "hashtag"]) 

for hashtag in hashtag_list:
    hashtag = hashtag.replace('\n','') 
    try:
        for i in tw.Cursor(api.search, q = hashtag, lang = "en", twitter_mode = 'extended').items(25): 
            tweets.append(i)

        one_hashtag_df = pd.DataFrame(vars(tweets[i]) for i in range(len(tweets)))  
        one_hashtag_df.dropna(subset=['text'], inplace=True)
        one_hashtag_df.drop_duplicates(subset='text', keep="last")
        one_hashtag_df = one_hashtag_df.drop(one_hashtag_df.index[150:])
        one_hashtag_df["hashtag"] = hashtag
        tw_all_hashtags = tw_all_hashtags.append(one_hashtag_df[["text", "hashtag"]], ignore_index=True)
        tweets = [] 
    except:
      print("Temporary error. Please try again later.") 

      
for i in range(len(tw_all_hashtags)):
    x = tw_all_hashtags.iloc[i]['text']
    tw_all_hashtags.iloc[i]['text'] = ' '.join(
        re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", x).split()) 
tw_all_hashtags['text'] = tw_all_hashtags['text'].str.replace('RT', '')
tw_all_hashtags.reset_index(drop=True).to_csv("tweets_hashtag.csv", index=False)

如您所见,我尝试将参数 twitter_mode = 'extended' 添加到 tw.Cursor 行,但这在最终的 CSV 文件中没有任何改变。我没有收到任何错误,但当我在 Excel 上查看推文时仍然只会被截断。对新手如何解决我的这个小问题有什么建议吗?提前致谢。干杯!

【问题讨论】:

    标签: python api csv twitter tweepy


    【解决方案1】:

    请改用tweet_mode = "extended"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-05
      • 2022-07-04
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2017-03-29
      相关资源
      最近更新 更多