我正试图通过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'])
有人可以帮我解决这个问题吗?
提前谢谢。
答案 0 :(得分:1)
你将太多东西混合在一起。如错误所示,您正在尝试解码字节类型。
json.loads
会将数据生成为字符串,您需要对其进行编码。
texts = json_load['text'] # string
coded = texts.encode('utf-8') # byte
print(coded[2:-1])
因此,在您的脚本中,当您尝试解码coded
时,您收到有关解码byte
数据的错误。