2015-08-27 36 views
2

我在使用tweepy並在屏幕(Windows)上打印tweet消息時出現此錯誤。'charmap'編解碼器無法編碼字符

#!/usr/bin/env python 

from tweepy import Stream 
from tweepy import OAuthHandler 
from tweepy.streaming import StreamListener 
import json 

#consumer key, consumer secret, access token, access secret. 
ckey = 'xyz' 
csecret = 'xyz' 
atoken = 'xyz' 
asecret = 'xyz' 


class Listener(StreamListener): 

    def on_data(self, data): 
     print json.loads(data)['text'] 
     return True 

    def on_error(self, status): 
     print status 


auth = OAuthHandler(ckey, csecret) 
auth.set_access_token(atoken, asecret) 

twitterStream = Stream(auth, Listener()) 
twitterStream.filter(track=['#hash1', '#hash2'], languages=['en']) 
> Traceback (most recent call last): File 
> "C:....twitterSentiment.py", 
> line 34, in <module> 
>  twitterStream.filter(track=['#hash1', '#hash2'], languages=['en']) File 
> line 430, in filter 
>  self._start(async) File "C:......streaming.py", 
> line 346, in _start 
>  self._run() File "C:.....streaming.py", 
> line 286, in _run 
>  raise exception UnicodeEncodeError: 'charmap' codec can't encode characters in position 108-111: character maps to <undefined> 

它是由Windows不支持所有字符引起的。有沒有解決方法?

+1

你可以在這裏發佈你的代碼嗎? pastebin –

+0

您需要粘貼錯誤引用的代碼,錯誤只是告訴我們在哪裏查找錯誤。 – PVNRT

回答

2

您會收到此錯誤消息,因爲它無法打印部分tweet.text。將其編碼爲utf-8(unicode)。

def on_data(self, data): 
    print json.loads(data)['text'].encode('utf-8') 
    return True 
0
chcp 65001 

這是在多線程在規定溶液。我正在使用未打印的符號「∞」。我運行後從cmd運行python代碼

chcp 65001 

它的工作方式就像一個魅力。希望能幫助到你。

p.s.它只能在cmd中工作,不能在原子編輯器中,也不能通過cygwin。

相關問題