2017-10-01 13 views
0

tweepy(Python 3.6)を使ってユーザのタイムラインツイートを取得しようとしています。さて、私はこれを行うことができるコードを見つけ、CVS形式で保存しました。これは英語のつぶやきを検索する際に問題なく動作しますが、アラビア語で書かれたつぶやきは次のように表示されます: "b '\ xd9 \ x82 \ xd8 \ xaa \ xd8 \ xa7 \ xd9 \ x84 \ x ..."私は複数のフォーラムを通過し、この問題が何度か起きているのを見ましたが、解決策を見つけることができませんでした。私はutf-8のエンコーディングと何か関係があるはずだと考えましたが、コードを操作する方法はわかりません。誰でも提案がありますか?ありがとう!CVSでtweepyからアラビアツイートを保存

これは私のコードです:Pythonの3.xでは

>>> 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") 

答えて

1

、今のシステムopen()コマンドとファイルへの書き込みのPython 2.xでテキストモード(、デフォルトを書くときencode()を呼び出す必要はありません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に変換します。

+0

こんにちは!この説明をいただきありがとうございます。残念ながら、CSVファイルを開くと、アラビア文字は次のように表示されます。بسبعد†ÙØØØÙÙ...نىØ'ÙÙ。 –

+0

CSVを開くために何を使用していますか? –

+0

ああ待ってください。良い質問!私はExcelを使用していましたが、TextEditでうまく動作することが分かりました!素晴らしい、ありがとう! Excelでなぜこのようなことが起こり、どのように克服できるのか、何らかの理由でご存じですか? –

関連する問題