解析JSON为CSV Twitter数据时KeyError: 'user
我现在正在处理一些我收集的推文数据,这些数据保存在一个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
3 个回答
1
你遇到了一个KeyError错误。这种错误通常是因为你在字典里查找一个不存在的键。如果你想检查某个键是否在字典里,可以这样做:
if 'user' in tweet:
tweets_location.append( tweet['user']['location'] )
或者你可以把它放在一个try..except结构里,这样可以捕捉到错误:
try:
tweets_location.append( tweet['user']['location'] )
except KeyError:
tweets_location.append('')
另外,你还可以使用字典的get方法,正如XrXrXr所建议的。get方法让你可以方便地提供一个默认值,也就是说,你可以用一行代码来完成:
tweets_location.append( tweet.get('user', '').get('location', '') )
如果'tweet'里没有'user'这个键,它会默认返回一个空字符串;同样,如果'tweet['user']'里没有'location'这个键,它也会返回一个空字符串。
2
使用 dict.get
方法。
if tweet.get('user'):
tweets_location.append(tweet['user'].get('location', ''))
else:
tweets_location.append("")
0
在这个if语句中,你用 tweet['user']
来获取数据,这样做是默认这个叫 user
的键一定存在。如果这个键不存在,就会出现 KeyError
错误。你可以通过 if 'user' in tweet
来检查这个键是否在字典里。或者,你也可以像处理 ValueError
一样来处理 KeyError
。
try:
....
try:
tweets_location.append( tweet['user']['location'] )
except KeyError:
tweets_location.append("")
except ValueError:
pass