【发布时间】:2016-11-25 20:38:45
【问题描述】:
我正在尝试使用 python 2.7.12 从 json 文件中读取 twitter 数据。
我使用的代码是这样的:
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def get_tweets_from_file(file_name):
tweets = []
with open(file_name, 'rw') as twitter_file:
for line in twitter_file:
if line != '\r\n':
line = line.encode('ascii', 'ignore')
tweet = json.loads(line)
if u'info' not in tweet.keys():
tweets.append(tweet)
return tweets
我得到的结果:
Traceback (most recent call last):
File "twitter_project.py", line 100, in <module>
main()
File "twitter_project.py", line 95, in main
tweets = get_tweets_from_dir(src_dir, dest_dir)
File "twitter_project.py", line 59, in get_tweets_from_dir
new_tweets = get_tweets_from_file(file_name)
File "twitter_project.py", line 71, in get_tweets_from_file
line = line.encode('ascii', 'ignore')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte
我查看了类似问题的所有答案,并想出了这段代码,它上次工作。我不知道为什么它现在不起作用...我将不胜感激!
【问题讨论】:
标签: json python-2.7 utf-8 ascii python-unicode