首页 > 解决方案 > 我应该如何清理从 twitter API 检索到的这些数据?

问题描述

这个脚本我从 Twitter API 中检索推文并将它们保存到一个 csv 文件中。目前,问题是推文完全打印在 csv 文件中,并且在一些推文中间仍然包含空格的文本位以及诸如“\xe2\x80\x99”之类的文本应该有成为标点符号。我尝试了以下方法:

for tweet in tweepy.Cursor(api.search,q=search_words,lang="en",since=date_since, tweet_mode = "extended").items(200):
    tweet = tweet.strip()

但出现以下错误:

AttributeError: 'Status' object has no attribute 'strip'

也尝试添加该行:

如果 tweet.find('\xe') :继续

得到了这个:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-2: truncated \xXX escape

这是我的完整代码:

import tweepy
import csv

consumer_key=""
consumer_secret=""

access_token=""
access_token_secret=""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)


search_words = "gender -filter:retweets"
date_since = "2021-01-28"


#tweets = tweepy.Cursor(api.search, q=search_words, lang="en",since=date_since).items(100)

# open and create a file to append the data to
csvFile = open('results.csv', 'a')
csvWriter = csv.writer(csvFile)
# use the csv file
# loop through the tweets variable and add them to the CSV file
for tweet in tweepy.Cursor(api.search,q=search_words,lang="en",since=date_since, tweet_mode = "extended").items(200):
    tweet.strip()
    if tweet.find('\xe') : continue
    csvWriter.writerow([tweet.full_text.encode('utf-8')])
    print(tweet.created_at, tweet.full_text)
csvFile.close()

尝试运行此代码并查看 csv 文件以查看我自己遇到的问题。请让我知道我应该如何清理这些推文。

标签: pythoncsvtwitterunicodetweepy

解决方案


推荐阅读