0

我正在尝试通过 textblob 库中的情绪分析从 twitter api 运行文本,当我运行我的代码时,代码会打印一个或两个情绪值,然后出错,出现以下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 31: ordinal not in range(128)

如果仅分析文本,我不明白为什么这是代码要处理的问题。我试图将脚本编码为 UTF-8。这是代码:

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import sys
import csv
from textblob import TextBlob

# Variables that contains the user credentials to access Twitter API
access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""


# This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
    def on_data(self, data):
        json_load = json.loads(data)
        texts = json_load['text']
        coded = texts.encode('utf-8')
        s = str(coded)
        content = s.decode('utf-8')
        #print(s[2:-1])
        wiki = TextBlob(s[2:-1])

        r = wiki.sentiment.polarity

        print r

        return True

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

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, StdOutListener())

# This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['dollar', 'euro' ], languages=['en'])

有人可以帮我解决这个问题吗?

先感谢您。

4

1 回答 1

1

你把太多东西混在一起了。正如错误所说,您正在尝试解码字节类型。

json.loads将导致数据作为字符串,您需要对其进行编码。

texts = json_load['text'] # string
coded = texts.encode('utf-8') # byte
print(coded[2:-1])

因此,在您的脚本中,当您尝试解码时,您会收到有关解码数据coded的错误。byte

于 2015-06-19T22:41:58.173 回答