1

Twitter 検索 API で Java を使用してツイートを mongoDB に保存しています。Twitter API からの json をそのまま保存する方法はありますか?

私もpythonの使用を検討していますが、pythonでそれを行う方法はありますか?

4

1 に答える 1

1

あなたがまだこれに対する答えに興味があるかどうかはわかりませんが、純粋にPythonの立場から、これは生のツイートjsonを保存する方法です:

import tweetstream # Needed For Twitter API Capture (Make sure using modified version with proxy support)
import argparse    # Needed for taking cmd line input
import gzip        # Needed for compressing output
import json        # Needed for Data conversion for easier DB import
import ast         # Also Needed for Data conversion

collector = argparse.ArgumentParser(description='Collect a lot of Tweets')        # This line sets up the argument collector
collector.add_argument('--username', dest='username', action="store")             # This line collects the Username
collector.add_argument('--password', dest='password', action="store")             # This line collects the password
collector.add_argument('--outputfilename', dest='outputfilename', action="store") # This line collects the output filename

args = collector.parse_args()                                                     # Setup args to store cmd line arguments

def printusername():                                                              # define the username argument

        print args.username

def printpassword():                                                              # define the password argument

        print args.password

def printoutputfilename():                                                        # define the output filename

        print args.outputfilename

output=gzip.open(args.outputfilename, "a")                                        # Open the output file for GZIP writing

with tweetstream.TweetStream(args.username, args.password) as stream:             # Open the Twitter Stream
    for tweet in stream:                                                          # For each tweet within the twitter stream
        line = str(tweet)                                                         # turn the tweet into a string
        line = ast.literal_eval(line)                                             # evaluate the python string (dictionary)
        line = json.dumps(line)                                                   # turn the python dictionary into valid JSON
        output.write(line)                                                        # write the line to the output file
        output.write("\n")  

これを実行するには: "python myscript.py --username yourusername --password yourpassword --outputfilename yourpathandfilename"

tweetstream argparse gzip json および ast モジュールをインストールする必要があります。これらはすべて、pip または easy_install またはほとんどの ubuntu/fedora パッケージ マネージャーを介してインストールできます。

スクリプトが作成する出力ファイルは単純な gzip 圧縮テキスト ファイルで、各行は完全なツイート json オブジェクトを含む新しい json 文字列です。スクリプトはレート制限に達するまで実行されるため、適切な EOF で gzip ファイルを閉じません。ただし、python は気にしないので、別のスクリプトで開くことができます。また、7zip や winrar も同様です。

それが役立つことを願っています。:)

于 2012-05-27T04:06:05.080 に答える