无法读取解析推文时的所有文本json格式?

-1 投票
1 回答
1690 浏览
提问于 2025-04-17 19:38

我在尝试写一个Python程序,从一个JSON格式的文件中提取推文的文本(不包括转发的推文)。下面是我写的Python代码片段(文件很大,有20MB,所以这里没有包含)。

import sys
import difflib
import twitter
import json
from pprint import pprint

# Input argument is the filename of the JSON ascii file from the Twitter API

filename = sys.argv[1]
tweets_text = [] # We will store the text of every tweet in this list
tweets_location = [] # Location of every tweet (free text field - not always `enter code here`accurate or given)
tweets_timezone = [] # Timezone name of every tweet

# Loop over all lines
f = file(filename, "r")
lines = f.readlines()
for line in lines:
    try: 
        tweet = json.loads(line)

        # Ignore retweets!
        if (tweet[1].has_key('retweeted_status') or not ( tweet[1].has_key('text'))): 
            continue

            # Fetch text from tweet
            text = tweet[1]['text'].encode('utf-8','ignore').lower()

            # Ignore 'manual' retweets, i.e. messages starting with RT      
            if text.find("RT ") > -1:
                continue

        tweets_text.append( text )
        tweets_location.append( tweet[1]['user']['location'].encode('utf-8','ignore') )
        tweets_timezone.append( tweet[1]['user']['time_zone'].encode('utf-8','ignore') )

    except ValueError:
        pass

# Show result
print tweets_text

问题是我只提取到了一个推文。有人能帮我找出错误吗?

1 个回答

1

你正在逐行读取一个json文件,并且把每一行都当作有效的JSON来加载,但实际上它可能并不是有效的。你可以试试下面的做法:

    lines = f.readlines()
    tweet = json.loads(lines)

这样一来,你就可以通过tweet来访问所有的JSON元素了。

编辑:假设你的JSON结构和这个链接返回的内容一样:https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

你可以这样做:

    f = file(filename,"r")
    lines = f.readlines()
    tweets_json = json.loads(lines[0])
    for tweet in tweets_json:
        if tweet['retweeted'] == False:
            tweets_text.append(tweet['text'])

    print tweets_text

撰写回答