将JSON解析为CSV Twitter数据KeyError:“用户" [英] Parse JSON to CSV Twitter Data KeyError: 'user'
问题描述
我正在尝试解析我现在收集在JSON文件中的一些推文数据.问题是某些推文中没有用户"或位置".结果,我收到如下消息:
I am trying to parse some tweets data I collected in a JSON file right now. The problem is some of the tweets don't have 'user' or 'place' in them. As a result, I get messages like:
File "<stdin>", line 18, in <module>
KeyError: 'user'
所以我试图添加一个if-else语句,但是它仍然给我错误消息.你下一步怎么做?
So I tried to add an if-else statement, but it is still giving me the error message. What is the next step?
for line in lines:
try:
tweet = json.loads(line)
# Ignore retweets!
if tweet.has_key("retweeted_status") or not tweet.has_key("text"):
continue
# Fetch text from tweet
text = tweet["text"].lower()
# Ignore 'manual' retweets, i.e. messages starting with RT
if text.find("rt ") > -1:
continue
tweets_text.append( text )
# I added an if-else statement, but it's still having be the error message
if tweet['user']:
tweets_location.append( tweet['user']['location'] )
else:
tweets_location.append("")
except ValueError:
pass
推荐答案
通过在if语句中执行 tweet ['user']
,您假设键 user
存在,这会引发 KeyError
.您可以通过在推特中执行 if'user'
来测试密钥是否在字典中.另外,您可以像处理 ValueError
By doing tweet['user']
in the if statement you are assuming the key user
exist, which raises the KeyError
. You can test if the key is in the dict by doing if 'user' in tweet
. Alternatively, you can handle the KeyError
similar to how to handle ValueError
try:
....
try:
tweets_location.append( tweet['user']['location'] )
except KeyError:
tweets_location.append("")
except ValueError:
pass
这篇关于将JSON解析为CSV Twitter数据KeyError:“用户"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!