簡體   English   中英

嘗試將Tweets流另存為json時出現Tweepy的UnicodeEncodeError

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

所以我試圖保存通過Tweepy在Python上流式傳輸的Tweets。 我正在使用此代碼->

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)

我嘗試使用谷歌搜索答案,但找不到與該特定問題相關的任何內容。 有人能幫我嗎?

您具有Python 2 str不支持的非ascii字符。 只需刪除文件中的str().write(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM