使用Python获取Twitter数据时出现Unicode解码错误

3

当检索特定阿拉伯语关键词的 Twitter 数据时,请按以下方式操作:

#imports
from tweepy import Stream
from tweepy import OAuthHandler 
from tweepy.streaming import StreamListener

#setting up the keys
consumer_key = '………….' 
consumer_secret = '…………….'
access_token = '…………..'
access_secret = '……...'

class TweetListener(StreamListener):
    # A listener handles tweets are the received from the stream.
    #This is a basic listener that just prints received tweets to standard output

    def on_data(self, data):
        print (data)
        return True

    def on_error(self, status):
        print (status)

    #printing all the tweets to the standard output
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)

    stream = Stream(auth, TweetListener())
    stream.filter(track=['سوريا'])

我收到了这个错误信息:
Traceback (most recent call last):
File "/Users/Mona/Desktop/twitter.py", line 29, in <module>
stream.filter(track=['سوريا'])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/tweepy/streaming.py", line 303, in filter
encoded_track = [s.encode(encoding) for s in track]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position 0: ordinal not in range(128)

请帮忙!任何帮助都可以!
1个回答

6
我查看了 tweepy 的源代码,并在 Stream 的源代码中找到了这一行 引起问题的代码。这一行是来自 filter 方法。当您在您的代码中调用 stream.filter(track=['سوريا']) 时,Stream 调用 s.encode('utf-8'),其中 s = 'سوريا'(查看 filter 的源代码,您会发现 utf-8 是默认编码)。就在这个点上,代码会抛出异常。
要解决这个问题,我们需要使用 Unicode 字符串。
 t = u"سوريا"
 stream.filter(track=[t])

(我只是为了清晰起见将您的字符串放入变量t中)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接