0

抱歉,我只是想将每条推文中的 'id_str' 存储到一个名为 ids[].. 的新列表中,但出现以下错误:

Traceback(最近一次调用最后一次):文件“extract_tweet.py”,第 17 行,在 print tweet['id_str'] KeyError: 'id_str'

我的代码是:

import json
import sys
if __name__ == '__main__':
tweets = []
for line in open (sys.argv[1]):
try:
  tweets.append(json.loads(line))
except:
  pass
ids = []
for tweet in tweets:
ids.append(tweet['id_str'])
4

2 回答 2

2

来自推文的 json 数据有时会丢失字段。试试这样的,

ids = []
for tweet in tweets:
    if 'id_str' in tweet:
        ids.append(tweet['id_str'])

或等效地,

ids = [tweet['id_str'] for tweet in tweets if 'id_str' in tweet]
于 2013-05-19T00:15:04.957 回答
0
import json

tweets = []
tweets.append(
        json.loads('{"a": 1}')
)
tweet = tweets[0]
print(tweet)
print( tweet['id_str'] )

--output:--
{'a': 1}

Traceback (most recent call last):
  File "1.py", line 9, in <module>
    print( tweet['id_str'] )
KeyError: 'id_str'

和:

my_dict = {u"id_str": 1}
print my_dict["id_str"]

--output:--
1
于 2013-05-19T00:08:21.133 回答