密钥存在时的KeyError [英] KeyError when Key exists
问题描述
使用python和twitter api获取tweet对象.
Using python and twitter api to get tweet objects.
我有一个带有推文的文件(我的计算机上是tweetfile = .txt文件),我试图遍历对象以获取文本.我使用tweetObj.keys()检查了twitter对象,以查看密钥和文本"是否存在;但是,当我尝试使用tweetObj ['text']获取单个文本时,出现了KeyError:'text'
I have a file (tweetfile = a .txt file on my computer) with tweets and I'm trying to loop through the objects to get the text. I checked the twitter object with tweetObj.keys() to see the keys and 'text' is there; however, when I try to get the individual text using tweetObj['text'] I get the KeyError: 'text'
代码:
for line in tweetfile:
tweetObj = json.loads(line)
keys = tweetObj.keys()
print keys
tweet = tweetObj['text']
print tweet
下面是输出:
[u'contributors', u'truncated', u'text', u'in_reply_to_status_id', u'id', u'favorite_count', u'source', u'retweeted', u'coordinates', u'entities', u'in_reply_to_screen_name', u'id_str', u'retweet_count', u'in_reply_to_user_id', u'favorited', u'user', u'geo', u'in_reply_to_user_id_str', u'possibly_sensitive', u'lang', u'created_at', u'filter_level', u'in_reply_to_status_id_str', u'place']
@awe5sauce my dad was like "so u wanna be in a relationship with a 'big dumb idiot'" nd i was like yah shes the bae u feel lmao
[u'delete']
Traceback (most recent call last):
File "C:\apps\droid\a1\tweets.py", line 34, in <module>
main()
File "C:\apps\droid\a1\tweets.py", line 28, in main
tweet = tweetObj['text']
KeyError: 'text'
我不确定该如何处理,因为它看起来像打印一条tweet.问题是,为什么会在该键存在并且似乎返回一个值但不针对所有实例的情况下发生这种情况,又该如何将其更正为可以使用该键访问所有行的值的地方?
I'm not sure how to approach since it looks like it prints one tweet. The question is why would this occur where the key exists and appears to return a value but not for all instances and how can I correct it to where I can access the value for all lines with that key?
推荐答案
循环中创建了2个字典,每行一个.第一个具有text
,第二个仅具有'delete'
键.它没有'text'
键.因此,错误消息.
There are 2 dictionaries created within the loop, one for each line. The first one has text
and the second one only has a 'delete'
key. It does not have the 'text'
key. Hence the error message.
将其更改为:
for line in tweetfile:
tweetObj = json.loads(line)
keys = tweetObj.keys()
print keys
if 'text' in tweetObj:
print tweetObj['text']
else:
print 'This does not have a text entry'
请注意,如果您仅对包含text
的行感兴趣,则可以使用
Just so you know, if you are only interested in the lines containing text
, you may want to use
[ json.loads(l)['text'] for l in tweetfile if 'text' in json.loads(l) ]
或
'\n'.join([ json.loads(l)['text'] for l in tweetfile if 'text' in json.loads(l) ])
甚至更好
[ json.loads(l).get('text') for l in tweetfile]
这篇关于密钥存在时的KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!