【问题标题】:exporting output to csv file?将输出导出到 csv 文件?
【发布时间】:2018-05-08 23:26:29
【问题描述】:

我有一个代码可以从它的 ID 中获取一条推文,我想将输出导出到 csv 文件。 代码如下:

import tweepy
from tweepy import OAuthHandler
import csv 

consumer_key = '???'
consumer_secret = '???'
access_token = '???'
access_secret = '???'


auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)


tweet = api.get_status(/id of tweet/)
print(tweet.text)
print(tweet.id)
print(tweet.created_at)

我尝试了这个代码,我从其他代码中得到它,但它不起作用:

with open('tweet1212.csv', 'w',encoding='utf-8') as csvfile:
        fieldnames = ['info.']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(tweet)

它让我着迷:

TypeError: 'Status' object is not iterable

如果可以,请帮助我。

【问题讨论】:

  • 请帮忙!

标签: python csv twitter export export-to-csv


【解决方案1】:

错误告诉你出了什么问题——你不能只将“状态”对象传递给写入者。

快速浏览document 会发现writerow 需要字典。

所以有两种方法:

with open('tweet1212.csv', 'w',encoding='utf-8') as csvfile:
    fieldnames = ['info.']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    row = str(tweet.text) + str(tweet.id) + str(tweet.created_at)
    writer.writerow({'info.':row})

或者您可以将字段名称更改为fieldnames=['text', 'id','created_at'],然后执行write.writerow({'text':tweet.text, 'id':tweet.id, 'created_at':tweet.created_at})之类的操作

这样你每次打开文件时都会写一行,所以我怀疑你想追加a而不是写w

with open('tweet1212.csv', 'a',encoding='utf-8') as csvfile:

让我知道它是否有效/您需要更多帮助!

附:我强烈建议使用 pandas 而不是 csv 来创建 csv 文件 - 操作数据框要容易得多!

编辑1

假设您通过运行此函数获得一条新推文:

tweet = api.get_status(/id of tweet/)

那么您可以通过以下方式构建推文列表:

allTweets=[];
allIDs=[1234, 1235, 1236] # a lits of id of tweets that you want to get

with open('tweet1212.csv', 'a',encoding='utf-8') as csvfile:
    fieldnames = ['info.']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for ID in allIDs:
        tweet = api.get_status(/id of tweet/)
        row = str(tweet.text) + str(tweet.id) + str(tweet.created_at)
        writer.writerow({'info.':row})

让我知道它是否有效!

【讨论】:

  • 这是一个很好的解决方案,但并不完全有效。因为代码只写了一行,我做了你说的我把 w 换成了 a 并且没有用。对不起,如果我打扰了你。
  • 我的朋友代码只写了一行,我附加了 'a' 而不是 'w' 并且没有任何改变。
  • 我正在处理更新,很快就会回复您!
  • 每次我运行代码时它都会附加到 csv 文件中,所以对我来说似乎没问题。你的意思是你想一次写很多行?
  • 不完全工作,但没问题第一个解决方案很好。在另一个主题中,我想问你是否有 python 代码可以从特定的推文中获取回复?
猜你喜欢
  • 1970-01-01
  • 2015-01-17
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多