在 CVS 中保存来自 tweepy 的阿拉伯语推文

Saving arabic tweets from tweepy in CVS

我正在尝试使用 tweepy (Python 3.6) 检索用户的时间线推文。现在,我找到了一个代码,我可以用它来做到这一点并将它们保存为 CVS 格式。它在检索英文推文时没有问题,但用阿拉伯语写的推文却以这种方式显示:"b'\xd9\x82\xd8\xaa\xd8\xa7\xd9\x84\x..."。我浏览了多个论坛,看到这个问题被多次提出,但我一直无法找到解决方案。我认为它一定与编码 utf-8 有关,但我不知道如何操作代码。有人有建议吗?谢谢!

这是我的代码:

>>> import tweepy
>>> import csv
>>> consumer_key = "..."
>>> consumer_secret = "..."
>>> access_key = "..."
>>> access_secret = "..."
>>> def get_all_tweets(screen_name):

#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

#initialize a list to hold all the tweepy Tweets
alltweets = []  

#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name = screen_name,count=200)

#save most recent tweets
alltweets.extend(new_tweets)

#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1

#keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
    print("getting tweets before %s" % (oldest))

    #all subsiquent requests use the max_id param to prevent duplicates
    new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #update the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    print("...%s tweets downloaded so far" % (len(alltweets)))

#transform the tweepy tweets into a 2D array that will populate the csv 
outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]

#write the csv  
with open('%s_tweets.csv' % screen_name, 'w') as f:
    writer = csv.writer(f)
    writer.writerow(["id","created_at","text"])
    writer.writerows(outtweets)

pass

>>> if __name__ == '__main__':
#pass in the username of the account you want to download
get_all_tweets("#username")

在Python3.x中,写入文件时无需调用encode(),因为系统open()命令现在默认为文本模式(在Python2.x,可以用io.open())

tweet.text.encode("utf-8") 更改为 tweet.text

由于 Python 3 使用您的语言环境来确定以文本模式打开文件时要使用的文件编码,因此将 open() 代码更改为更安全:

with open('%s_tweets.csv' % screen_name, 'w', encoding='utf-8') as f:

现在,Python 将在写入文件时自动将任何字符串编码为 UTF-8。