【问题标题】:'charmap' codec can't encode characters“charmap”编解码器无法编码字符
【发布时间】:2015-11-21 06:47:54
【问题描述】:

我正在使用 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 不支持所有字符造成的。有解决办法吗?

【问题讨论】:

  • 你能把你的代码贴在这里吗?粘贴箱
  • 您需要粘贴错误引用的代码,错误只是告诉我们在哪里查找错误。

标签: python twitter tweepy


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    chcp 65001
    

    这是多线程中规定的解决方案。我使用了一个没有被打印出来的符号“∞”。运行后我从cmd运行了python代码

    chcp 65001
    

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

    附言它只能在 cmd 中工作,而不是在 atom 编辑器中或通过 cygwin。

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 2018-08-25
      • 1970-01-01
      相关资源
      最近更新 更多