【问题标题】:How to export tweets to txt or json, by tweepy?如何通过 tweepy 将推文导出为 txt 或 json?
【发布时间】: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


    【解决方案1】:

    如果您尝试将 tweet 写入 JSON 文件,json.dump 将尝试将其转换为 JSON 格式。这个过程称为serializationjson.dump 仅支持默认编码器中的一小组类型,您可以阅读有关 in the Python documentation 的信息。由于 tweeps 用来表示推文的类不属于这些类型,json 模块会引发您提到的异常。

    作为一种解决方案,您可以序列化包含有关推文的各种数据的字典,这是一个示例:

    def tweet_to_json(tweet):
        tweet_dict = {
            "text": tweet.text,
            "author_name": tweet.user.screen_name
        }
        with open('tweet.json', 'w+') as f:
            json.dump(tweet_dict, f)
    

    请注意,对 JSON 文件使用附加模式通常不是一个好主意。您可以改用 JSON 列表。 This reply to another question 可能会帮助你。

    编辑:以下是保存 JSON 列表的示例:

    result = []
    for tweet in api.user_timeline(id=name, count=tweetCount):
        result.append({
            'text': tweet.text, 
            'author_name': tweet.user.screen_name
        })
    with open('tweet.json', 'w+') as f:
        json.dump(result, f)
    

    【讨论】:

    • 谢谢 Volcyy,唯一的问题是“w +”参数。他仍然只抄写一行。但是,我改为“a +”并得到了一些答案。 Volcoyy,你能告诉我如何解决输出是'utf-8'吗?即使在函数 encoding = 'utf-8' 内传递,答案还是一样。
    • 我认为您在这里将编码误认为是不同的东西。您尝试使用附加模式(open 中的 a 标志)将新数据添加到 JSON 文件,但这会弄乱 JSON 文件的格式,所以我不认为 encoding 标志是这里的问题。您可以使用我链接的答案中的 JSON 列表。我在答案中添加了一个示例。
    猜你喜欢
    • 2014-06-25
    • 2012-08-06
    • 1970-01-01
    • 2017-08-20
    • 2022-01-20
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 2017-11-05
    相关资源
    最近更新 更多