Twitter API Python - sys.argv 和 json

1 投票
1 回答
1114 浏览
提问于 2025-04-17 10:17

我在这个网站上发现了这个内容:http://pastebin.com/bqj3bZhG

"""
Simple Python example showing how to parse JSON-formatted Twitter messages+metadata
(i.e. data produced by the Twitter status tracking API)

This script simply creates Python lists containing the messages, locations and timezones
of all tweets in a single JSON file.

Author: Geert Barentsen - 4 April (#dotastro)
"""

import sys
import simplejson
import difflib

# 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 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 = simplejson.loads(line)

            # Ignore retweets!
            if tweet.has_key("retweeted_status") or not tweet.has_key("text"):
                    continue

            # Fetch text from tweet
            text = tweet["text"].lower()

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

            tweets_text.append( text )
            tweets_location.append( tweet['user']['location'] )
            tweets_timezone.append( tweet['user']['time_zone'] )

    except ValueError:
            pass


# Show result
print tweets_text
print tweets_location
print tweets_timezone

但是我用不了这个...

根据我的理解,我应该把json文件导入到
filename = sys.argv[1]

但是

import urllib
#twitteruser
user="gigmich"

#open twitter timeline request
filename = sys.argv[urllib.urlopen("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&contributor_details&include_rts=true&screen_name="+user+"&count=3600")]

对我来说似乎不太管用

你能帮我看看我该把json文件放在哪里吗

谢谢你的帮助!!!!

1 个回答

2

我觉得你对 sys.argv[1] 的意思有点混淆。在 pastebin 的链接中提到:

输入参数是来自 Twitter API 的 JSON ascii 文件的文件名

filename = sys.argv[1]

所以,首先你需要通过 Twitter API 下载你的 JSON ascii 文件,然后在运行你的脚本时,把这个文件名作为参数传进去,像这样:

python myscript.py jsonfile

在这里,jsonfile 就是 sys.argv[1]

而 myscript.py 就是 sys.argv[0]

撰写回答