【发布时间】:2014-08-18 01:28:39
【问题描述】:
我正在尝试解析我现在在 JSON 文件中收集的一些推文数据。问题是一些推文中没有“用户”或“地点”。结果,我收到如下消息:
File "<stdin>", line 18, in <module>
KeyError: 'user'
所以我尝试添加一个 if-else 语句,但它仍然给我错误消息。你下一步怎么做?
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
【问题讨论】: