이 코드는 여기에 있으며 완벽하게 작동합니다.텍스트 파일을 디코딩하는 방법
# 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)
해당 파일에 42,188 트윗이 있습니다,하지만 난 임은 (291)를 받고 코드를 실행할 때 내가 인코딩/디코딩 뭔가 생각하지만 난 알아낼 기운 다. 어떤 도움이라도 대단히 감사 할 것입니다.
인코딩/디코딩없이이 예제를 실행했는데 완벽하게 작동했습니다. 단지 291를 얻기의
http://adilmoujahid.com/posts/2014/07/twitter-analytics/
좋아, 나는 너희들이 나에게, 내가 해결하는거야 시도 해요 것으로, 많은 오류를 가지고 무엇을했다. 구분 기호 : 라인 1 컬럼 272 (char 271) 기대되는 ','구분 기호 : 라인 1 컬럼 202 (char 201) 기대되는 ','구분 기호 : 라인 1 컬럼 274 (char 273) 기대되는 ' , '구분 기호 : 줄 1 열 145 (문자 144) JSON 개체를 디코드 할 수 없습니다. –
확인하십시오. https://stackoverflow.com/questions/13675401/cant-read-json-file-in-python – Windsooon
가져 오려는 파일에는 구분 기호뿐만 아니라 셀의 문자 (예 : 쉼표가있는 문장)로 구분 문자가 사용되었습니다. –