2016-09-03 6 views
0

私はここにこのコードを書いています。テキストファイルを解読する方法

# encoding=utf8 
#Import the necessary methods from tweepy library 
import sys 
from tweepy import OAuthHandler 
from tweepy import Stream 
from tweepy.streaming import StreamListener 

reload(sys) 
sys.setdefaultencoding('utf8') 

#Variables that contains the user credentials to access Twitter API 
access_token = "" 
access_token_secret = "" 
consumer_key = "" 
consumer_secret = "" 

#This is a basic listener that just prints received tweets to stdout. 
class StdOutListener(StreamListener): 

    def on_data(self, data): 
     #save data 
     with open('debate_data.txt', 'a') as tf: 
      tf.write((data).decode('unicode-escape').encode('utf-8')) 

     return True 

    def on_error(self, status): 
     print status 

if __name__ == '__main__': 

    #This handles Twitter authetification and the connection to Twitter  Streaming API 
    l = StdOutListener() 
    auth = OAuthHandler(consumer_key, consumer_secret) 
    auth.set_access_token(access_token, access_token_secret) 
    stream = Stream(auth, l) 

    #This line filter Twitter Streams to capture data by the keywords:  'Bernier', 'Rossello', 'Bernabe' 
    stream.filter(track=['Bernier', 'Rosselló', 'Rossello', 'Bernabe', 'Lúgaro', 'Lugaro', 'María de Lourdes', 'Maria de Lourdes', 'Cidre']) 

しかし、このコードを実行すると、私は間違った答えを得ます。

import json 
import io 

#save the tweets to this path 
tweets_data_path = 'debate_data.txt' 

tweets_data = [] 
with io.open(tweets_data_path, 'r') as tweets_file: 
    for line in tweets_file: 
     try: 
      tweet = json.loads(line) 
      tweets_data.append(tweet) 
     except: 
      continue 

print len(tweets_data) 

は、そのファイル上の42188件のツイートはありますが、私はイムだけで291を取得コードを実行するとき、私はエンコード/デコードで何かだと思うが、私は何を把握傾けます。どんな助けでも大いに感謝するでしょう。

私はこの例をエンコード/デコードせずに実行しましたが、完全に機能しました。

http://adilmoujahid.com/posts/2014/07/twitter-analytics/

答えて

2

のみ291を取得する理由はjson.loads()は、いくつかのエラーをスローし、exceptそれを継続しています。

私はあなただけのようなエラーを印刷するお勧め:今、あなたは、エラーの理由を知っているし、それを解決

except Exception as err: 
    print err 
    continue 

debate_data.txtのデータ形式は、jsonですか?

2

agneweeが言ったように、私もお勧めします。

try: 
    tweet = json.loads(line) 
except Exception as err: 
    print err # or use log to see what happen 
else: 
    tweets_data.append(tweet) 
+0

[OK]を、私はあなたたちは私が修正するつもり試みだと、私に言った、エラーの多くを得たものでした。区切り記号:1行目272(char 271)区切り文字:1行目202(char 201)区切り文字:1区切り文字274(char 273) 、 '区切り文字:行1列145(文字144)JSONオブジェクトをデコードできませんでした –

+0

これをチェックしてくださいhttps://stackoverflow.com/questions/13675401/cant-read-json-file-in-python – Windsooon

+0

私がインポートしたいファイルには区切り文字としての区切り文字だけでなく、カンマ付きの文など、セル内の文字としての区切り文字も含まれていました。 –

関連する問題