-1

pythonでjsonファイル形式のツイート(リツイートを除く)のテキストを抽出するpythonプログラムを書いてみます。以下は Python のスニップコードです (ファイルが 20 MB と大きいため、ここには含まれていません)。

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 つしかないことです。誰でもエラーを指摘できますか?

4

1 に答える 1

1

json ファイルを 1 行ずつ読み込んでいて、有効な 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
于 2013-03-19T15:06:52.837 に答える