简体   繁体   English

尝试将Tweets流另存为json时出现Tweepy的UnicodeEncodeError

[英]UnicodeEncodeError with Tweepy when trying to save Stream of Tweets as json

So I am trying to save the Tweets I am streaming through Tweepy on Python. 所以我试图保存通过Tweepy在Python上流式传输的Tweets。 I am using this code --> 我正在使用此代码->

class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
    print (status.text)

def on_data(self, data):
    json_data = json.loads(data)
    file.write(str(json_data))

def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True


sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=['#GDPR'])

So when I run the code, this what the console throws out --> 因此,当我运行代码时,控制台会抛出->

sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=['GDPR'])
Traceback (most recent call last):

File "<ipython-input-20-564026ea611c>", line 2, in <module>
sapi.filter(track=['GDPR'])

File "/Users/Sweeties/anaconda/lib/python3.6/site-packages/tweepy/streaming.py", line 445, in filter
self._start(async)

File "/Users/Sweeties/anaconda/lib/python3.6/site-packages/tweepy/streaming.py", line 361, in _start
self._run()

File "/Users/Sweeties/anaconda/lib/python3.6/site-packages/tweepy/streaming.py", line 294, in _run
raise exception

File "/Users/Sweeties/anaconda/lib/python3.6/site-packages/tweepy/streaming.py", line 263, in _run
self._read_loop(resp)

File "/Users/Sweeties/anaconda/lib/python3.6/site-packages/tweepy/streaming.py", line 324, in _read_loop
self._data(next_status_obj)

File "/Users/Sweeties/anaconda/lib/python3.6/site-packages/tweepy/streaming.py", line 297, in _data
if self.listener.on_data(data) is False:

File "<ipython-input-16-674fb26e0cb4>", line 7, in on_data
file.write(str(json_data))

UnicodeEncodeError: 'ascii' codec can't encode characters in position 133-134: ordinal not in range(128)

I tried googling the answer, but I was not able to find anything related to this particular problem. 我尝试使用谷歌搜索答案,但找不到与该特定问题相关的任何内容。 Can someone help me? 有人能帮我吗?

You have non-ascii characters that's not supported by Python 2 str. 您具有Python 2 str不支持的非ascii字符。 Just get rid of the str() in your file.write(...) 只需删除文件中的str().write(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM