Python Tweepy:调整JSON输出
我使用这段代码通过搜索API提取推文。到目前为止,我只使用jsonpickle提取了整个JSON。但是,我只想从JSON中提取特定信息,如Python Tweepy:调整JSON输出,python,json,api,twitter,tweepy,Python,Json,Api,Twitter,Tweepy,我使用这段代码通过搜索API提取推文。到目前为止,我只使用jsonpickle提取了整个JSON。但是,我只想从JSON中提取特定信息,如tweet.id、tweet.全文或tweet.favorite\u count,并将其存储在CSV文件中。有人知道我如何在不更改max\u id/自\u id结构的情况下为此目的修改代码吗 import sys import jsonpickle import os import tweepy consumer_key = "XXXXXXXXXXXXX"
tweet.id
、tweet.全文
或tweet.favorite\u count
,并将其存储在CSV文件中。有人知道我如何在不更改max\u id
/自\u id
结构的情况下为此目的修改代码吗
import sys
import jsonpickle
import os
import tweepy
consumer_key = "XXXXXXXXXXXXX"
consumer_secret = "XXXXXXXXXXX"
auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
if (not api):
print ("Can't Authenticate")
sys.exit(-1)
searchQuery = 'XXXX'
maxTweets = XXX # number of tweets one wants to extract
tweetsPerQry = 100 # the max tweets the API permits per query
fName = 'tweets_keyword' # storing the tweets in a text file
sinceId = None
tweets = []
max_id = -1
tweetCount=0
print("Downloading max {0} tweets".format(maxTweets))
with open(fName+".csv", 'w') as file:
while tweetCount < maxTweets:
try:
if (max_id <= 0):
if (not sinceId):
new_tweets = api.search(q=searchQuery, count=tweetsPerQry, lang = 'en', tweet_mode = 'extended')
else:
new_tweets = api.search(q=searchQuery, count=tweetsPerQry, lang = 'en',tweet_mode = 'extended',
since_id=sinceId)
else:
if (not sinceId):
new_tweets = api.search(q=searchQuery, count=tweetsPerQry,lang = 'en', tweet_mode = 'extended',
max_id=str(max_id - 1))
else:
new_tweets = api.search(q=searchQuery, count=tweetsPerQry,lang = 'en',tweet_mode = 'extended',
max_id=str(max_id - 1),
since_id=sinceId)
if not new_tweets:
print("No more tweets found")
break
for tweet in new_tweets:
file.write(jsonpickle.encode(tweet._json, unpicklable=False) +
'\n')
tweetCount += len(new_tweets)
print("Downloaded {0} tweets".format(tweetCount))
max_id = new_tweets[-1].id
except tweepy.TweepError as e:
# Just exit if any error
print("some error : " + str(e))
break
print ("Downloaded {0} tweets, Saved to {1}".format(tweetCount, fName))
导入系统
导入jsonpickle
导入操作系统
进口粗花呢
消费者密钥=“XXXXXXXXXXXX”
消费者_secret=“xxxxxxxxxx”
auth=tweepy.AppAuthHandler(使用者密钥,使用者密钥)
api=tweepy.api(身份验证、等待速率、限制=True,
等待(速率限制通知=真)
如果(非api):
打印(“无法验证”)
系统出口(-1)
searchQuery='XXXX'
maxTweets=XXX#要提取的推文数
tweetsPerQry=100#API允许的每个查询的最大tweet数
fName='tweets_keyword'#将tweets存储在文本文件中
sinceId=无
tweets=[]
max_id=-1
tweetCount=0
打印(“下载最大{0}条tweets”。格式(最大tweets))
打开(fName+“.csv”,“w”)作为文件:
tweetCount状态本身就有相关信息的属性。
您可以简单地使用它们,而不是原始的JSON
原始JSON表示为一个字典,这是标准的,因此您也可以像访问任何其他字典一样通过键访问它
而且,API
在任何时候都不会是虚假的