尝试将推文流保存为json时,带有Tweepy的UnicodeEncodeError

时间:2017-07-31 17:08:28

标签: python json python-3.x encoding tweepy

所以我试图保存我在Python上通过Tweepy传输的推文。我正在使用此代码 - >

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'])

因此,当我运行代码时,这就是控制台抛出的 - >

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)

我尝试使用Google搜索答案,但我无法找到与此特定问题相关的任何内容。有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

你有Python 2 str不支持的非ascii字符。只需删除file.write(...)

中的str()