2016-11-18 17 views
1

Twitterのデータを使用して簡単なテキスト解析を習得しようとしています。最終的には、特定の文字列でつぶやきを検索し、それらのお気に入りの数を分析することができます。しかし、今私は簡単な印刷と私のtxtファイルの検索をしようとしています。は、txtファイルの出力を解析できませんpython - ValueError:閉じたファイルの入出力操作

データをダウンロードして.txtファイルに保存する方法を理解しましたが、解析できるようです。私はMacでPython 3.5.2を使用しています。私はTextWranglerにコードを書いていて、ターミナルで実行しています。

この問題に関する他のドキュメントを見ましたが、わかりません。

ここに私のコードです。

import tweepy 
import sys 
import re 
consumer_key = 'xxxx' 
consumer_secret = 'xxxx' 
access_token = 'xxxx' 
access_token_secret = 'xxxx' 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_token_secret) 
api = tweepy.API(auth) 
api.statuses_lookup('realdonaldtrump', include_entities=True, trim_user=False, map_= False) 
tweetslist = [] 
print (api.statuses_lookup) 
trump_tweets = api.user_timeline('realdonaldtrump', count=100) 
sys.stdout = open('trump_tweet_output.txt', 'w') 
for tweet in trump_tweets: 
    print (tweet.text) 
sys.stdout.close() 

##the above code works fine, creates a .txt file with tweet text 

##but when I run the below-- (or any other command to analyze the file) 

f = open('trump_tweet_output.txt') 
line = f.readline() 
print (line) 
f(close) 

##I get: 'ValueError: I/O operation on closed file.' 
+1

あなたはsys.stdout' 'をいじりしているためです。ファイルに書き込むときは、 'f = open( 'trump_tweet_output.txt'、 'w')'を実行してから 'f.write(..)'を実行します。 –

答えて

3

問題は、この行から来ている:あなたはその後、標準出力ストリームをクローズアップ終了このファイルを閉じ

sys.stdout = open('trump_tweet_output.txt', 'w') 

さらにダウンしているため。

sys.stdoutを再割り当てする代わりに、ファイルに書き込むことをお勧めします。あなたがファイルを読み取ろうとしているとき

with open('trump_tweet_output.txt', 'w') as f: 
    for tweet in trump_tweets: 
     f.write(tweet + '\n') 

次に、あなただけ書くことができます。

with open('trump_tweet_output.txt') as f: 
    print(f.readline()) 
関連する問題