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

时间:2013-03-19 14:15:41

标签: python

我尝试编写python程序以使用python以json文件格式(不包括转推)提取tweet中的文本。以下是python中的snippcode(文件大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 个答案:

答案 0 :(得分:1)

您正在逐行读取json文件,并且您正在加载每一行,就好像它是一个有效的JSON,它可能不是。尝试类似:

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

从那里你应该能够通过推文访问所有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