密钥存在时的KeyError

dan*_*jai 3 python twitter dictionary keyerror

使用python和twitter api获取推文对象.

我有一个文件(tweetfile =我的计算机上的.txt文件)和推文,我试图循环对象来获取文本.我用tweetObj.keys()检查了twitter对象,看到键和'text'在那里; 但是,当我尝试使用tweetObj ['text']获取单个文本时,我得到了KeyError:'text'

码:

for line in tweetfile:
    tweetObj = json.loads(line)
    keys =  tweetObj.keys()
    print keys
    tweet = tweetObj['text']
    print tweet
Run Code Online (Sandbox Code Playgroud)

以下是输出:

[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'
Run Code Online (Sandbox Code Playgroud)

我不知道如何处理,因为它看起来像打印一条推文.问题是为什么会出现密钥存在并且似乎返回值而不是所有实例的情况,以及如何将其更正为可以访问具有该密钥的所有行的值的位置?

ssm*_*ssm 5

循环内创建了2个字典,每行一个.第一个有text,第二个只有一把'delete'钥匙.它没有'text'钥匙.因此错误消息.

将其更改为:

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'      
Run Code Online (Sandbox Code Playgroud)

只是你知道,如果你只对包含的行感兴趣text,你可能想要使用

[ 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]