将特定主题标签的推文保存到 JSON 文件

Save tweets of specific hashtag to JSON file

我是编程新手,正在将 python 应用到需要分析特定 Twitter 话题标签的项目中。我已成功显示特定主题标签的推文,但我无法将它们保存到 JSON 文件。

如有任何帮助,我将不胜感激

在我的代码下方:

#Import necessary libaries to access Twitter
import os
import tweepy as tw
import pandas as pd
import tweepy as OAuthHandler
# Access keys and tokens to Twitter 
consumer_key=''
consumer_secret=''
access_token=''
access_token_secret=''
#Access Twitter
auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
#this to allow us to generate multiple requests and skip the waiting time
api = tw.API(auth, wait_on_rate_limit=True)
 #Define the query of our search
#query='#Astrazeneca'
query=input('print selected hashtag starting with #: ')
tweets=tw.Cursor(api.search,q=query,lang='en').items(50)
#for tweet in tweets:
    #print(tweet.text)
# make the tweets in a list
all_tweets=[tweet.text for tweet in tweets]
all_tweets[0:5]
# Save tweets to JSON file 
import json
for tweet in all_tweets:
    with open('tweetsfile._json','w',encoding='utf8') as file:
        json.dump(tweet._json, file,sort_keys = True,indent = 4)

我收到的错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-4-a82813c9d641> in <module>
      3 for tweet in all_tweets:
      4     with open('tweet.text_json','w',encoding='utf8') as file:
----> 5         json.dump(tweet._json, file,sort_keys = True,indent = 4)

AttributeError: 'str' object has no attribute '_json'

当您创建列表 all_tweets 时,您正在调用 tweet.text,其中 returns 是 stringstring 没有属性 _json,但是您的 tweet 对象(在调用 .text 之前有。

将其更改为包含对象 tweet,这样应该可以在循环中调用 tweet._json

all_tweets=[tweet for tweet in tweets]