5

python と twitter api を使用してつぶやきオブジェクトを取得します。

ツイートを含むファイル (tweetfile = 私のコンピューター上の .txt ファイル) があり、オブジェクトをループしてテキストを取得しようとしています。キーを確認するために tweetObj.keys() で twitter オブジェクトをチェックしたところ、「テキスト」がそこにありました。ただし、tweetObj['text'] を使用して個々のテキストを取得しようとすると、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'

1つのツイートを出力するように見えるので、アプローチ方法がわかりません。問題は、キーが存在し、すべてのインスタンスではなく、値を返すように見える場所でこれが発生するのはなぜですか?そのキーを持つすべての行の値にアクセスできる場所に修正するにはどうすればよいですか?

4

1 に答える 1

7

ループ内には、各行に 1 つずつ、合計 2 つの辞書が作成されます。最初のものには鍵がtextあり、2番目のものには鍵しかありません'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'      

ご存知のように、 を含む行のみに関心がある場合は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]

于 2014-07-18T02:08:38.573 に答える