在Python中读取Twitter json文件时出现KeyErrors
我试图用从twitter收集的数据分析json文件,但当我试图搜索关键字时,它说找不到,但我可以看到它在那里。我试过两种不同的方法。我会把它们贴在下面。任何建议都很好 尝试#1:在Python中读取Twitter json文件时出现KeyErrors,python,json,twitter,pandas,keyerror,Python,Json,Twitter,Pandas,Keyerror,我试图用从twitter收集的数据分析json文件,但当我试图搜索关键字时,它说找不到,但我可以看到它在那里。我试过两种不同的方法。我会把它们贴在下面。任何建议都很好 尝试#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
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)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
KeyError: 'text'
尝试#2:与前面的步骤相同,但执行了一个循环
t=tweets[0]
tweet_text = [t['text'] for t in tweets]
错误:
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)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
KeyError: 'text'
(仅粘贴部分输出)
谢谢!如果您有任何建议,我们将不胜感激。并非您的所有推文都有“文本”
键。过滤掉这些内容或使用dict.get()
返回默认值:
tweet_text = [t['text'] for t in tweets if 'text' in t]
或
谢谢你,Martjin!我将尝试使用dict.get()函数