【发布时间】:2018-02-21 02:42:50
【问题描述】:
我正在使用 tweepy 来捕获推特数据,我想知道我是否可以将推文导出到 json、txt 或 csv 文件? 我的代码:
#coding = utf-8
import json
import tweepy
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
consumer_key = "my_consumer_key"
consumer_secret = "my_consumer_secret"
access_token = "my_acess_token"
access_token_secret = "my_acess_token_secret"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def saida_json(tweet):
with open('tweet.json', 'a', encoding='utf-8') as f:
json.dump(tweet, f)
def saida_txt(tweet):
with open('tweet.txt', 'a', encoding='utf-8') as f:
for linha in tweet:
f.write(tweet + '\n')
name = "usersl"
tweetCount = 20
public_tweets = api.home_timeline()
user_tweets = api.user_timeline(id=name, count=tweetCount)
for tweet in user_tweets:
print(tweet.user.screen_name, tweet.text)
saida_txt(tweet.text)
saida_json(tweet)
我曾尝试通过函数来做到这一点,但每次都遇到错误。在 txt 文件中,它只写入第一条推文和 json,通知“它没有被序列化”。 我的错误在哪里?
【问题讨论】:
标签: python json twitter tweepy