读取 Python 中的 Twitter json 文件时出现 KeyErrors

KeyErrors while reading Twitter json files in Python

我正在尝试用我从 Twitter 收集的数据分析一个 json 文件,但是当我尝试搜索关键字时,它说找不到它,但我可以看到它在那里。我尝试了两种不同的方式。我将在下面 post 它们。任何建议都会很棒。

尝试 #1:

import sys
import os
import numpy as np
import scipy
import matplotlib.pyplot as plt
import json
import pandas as pan

tweets_file = open('twitter_data.txt', "r")
for line in tweets_file:
     try:
            tweet = json.loads(line)
            tweets_data.append(tweet)
     except:
            continue
tweets = pan.DataFrame()
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)

尝试 #2:与前面的步骤相同,但改为循环

t=tweets[0]
tweet_text = [t['text'] for t in tweets]

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
KeyError: 'text'

如果我打印tweets_data,这就是我看到的。 'text',等等,肯定是有的。我缺一个角色吗?

>>> print(tweet_data[0])   
    {u'contributors': None, u'truncated': False, u'text': u'RT
    @iHippieVibes: \u2b50\ufe0fFAV For This Lace Cardigan \n\nUSE Discount
    code for 10% off: SOLO\n\nFree Shipping\n\nhttp://t.co/d8kiIt3J5f
    http://t.c\u2026', u'in_reply_to_status....

(只粘贴了部分输出)

谢谢!任何建议将不胜感激。

并非所有 你的推文有一个 'text' 键。过滤掉那些或使用 dict.get() 到 return 默认值:

tweet_text = [t['text'] for t in tweets if 'text' in t]

tweet_text = [t.get('text', '') for t in tweets]