python - How to export tweets to txt or json, by tweepy? -


i using tweepy capture twitter data, know if have how export tweets json, txt or csv file? code:

#coding = utf-8  import json import tweepy tweepy import oauthhandler tweepy import stream 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):     open('tweet.json', 'a', encoding='utf-8') f:         json.dump(tweet, f)  def saida_txt(tweet):     open('tweet.txt', 'a', encoding='utf-8') f:         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)  tweet in user_tweets:     print(tweet.user.screen_name, tweet.text)     saida_txt(tweet.text)     saida_json(tweet) 

i have tried through functions, every time run errors. in txt file, writes first tweet , json, informs "its not serelized". error guys?

if try write tweet json file, json.dump attempt convert json format. process called serialization. json.dump supports small set of types in default encoder, can read in python documentation. since class tweeps uses represent tweet not part of these types, json module raises exception mentioned.

as solution, serialize dictionary containing various data tweet, here's example:

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

note using append mode json files not idea. use json list instead. this reply question might this.

edit: here's example saving json list:

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

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -