【发布时间】:2021-07-08 04:38:12
【问题描述】:
我是编程新手,我正在将 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'
【问题讨论】:
标签: python json twitter tweepy twitterapi-python