首页 > 解决方案 > Tweepy 编码错误:UnicodeEncodeError:“UCS-2”编解码器无法对位置 14-14 中的字符进行编码:Tk 中不支持非 BMP 字符

问题描述

我在 StackOverflow 上阅读了其他一些答案,并且我(大致)知道问题所在:Tweepy 和 Python 在转换某些字符(很可能是比特币)时遇到了一些困难,我看到了一些解决方案,但我太编程挑战应用它们(你可以从我的用户名中猜到)。

将不胜感激任何帮助解决这个问题。使用最新的 Python 3.x。

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


#consumer key, consumer secret, access token, access secret.
ckey=""
csecret="" #Removed for privacy
atoken="" #Removed for privacy
asecret="" #Removed for privacy


class listener(StreamListener):

    def on_data(self, data):
        all_data = json.loads(data)

        tweet = all_data["text"]

        print((tweet))
        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=["car"])

标签: python-3.xunicodecharacter-encodingtweepypython-unicode

解决方案


我在网上找到了答案。

您添加一个 ascii 包装器:

推文 = ascii(all_data["text"])


推荐阅读