'charmap' 编解码器无法对字符进行编码

'charmap' codec can't encode characters

我正在使用 tweepy,在屏幕上打印推文消息时出现此错误 (Windows)。

#!/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不支持所有字符造成的。有解决办法吗?

您收到此错误,因为它无法打印 tweet.textunicode 部分。将其编码为 utf-8 (unicode)。

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

这是多线程中规定的解决方案。我使用的是没有打印出来的符号“∞”。我 运行 在 运行

之后来自 cmd 的 python 代码
chcp 65001

它就像一个魅力。希望对你有帮助。

p.s. It only works in cmd not in atom editor nor via cygwin.