【问题标题】:How can i get tweets into csv from the data i got from twitter with stream api我如何使用流 api 从 twitter 获得的数据中将推文导入 csv
【发布时间】:2016-06-04 13:40:04
【问题描述】:

我正在使用 Tweepy 并使用 Stream API 从 Twitter 获取数据...这是我的 t_stream.py 文件:

access_token = "my token"
access_token_secret = "my t_secret"
consumer_key = "my key"
consumer_secret = "my c_secret"

class StdOutListener(StreamListener):
    def on_data(self, raw_data):
        data = json.loads(raw_data)
        print(json.dumps(data, ensure_ascii=False))

    def on_error(self, status):
        print (status)

if __name__ == '__main__':

    dinle = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, dinle)

当我使用代码时,我有一个名为 veri.txt 的文件:

    python3 t_stream.py > veri.txt

这是部分结果数据:https://paste.pound-python.org/show/SiUalejehr6T8BEvYOpw/

从这个 veri.txt 文件中,我想获取如下信息:

转推数:

followers_count:

姓名:

文本:

我想将这些列存储为输出 csv 文件... 我尝试了一些代码,但没有奏效。因此,我要求使用 python 代码逐行读取文本文件,从行中获取我上面提到的信息并将它们作为列存储在数据文件中作为 csv 文件。有人可以帮我解决这个问题吗?谢谢。

【问题讨论】:

  • 我找到了解决方案:print(json.dumps(data['text'], ensure_ascii=False))

标签: python csv twitter stream


【解决方案1】:

来自python3 docs的一些例子:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

【讨论】:

    【解决方案2】:

    不是 python 示例,但您可以使用 jq 过滤器非常轻松地管道输出流。

    $ oksocial https://stream.twitter.com/1.1/statuses/sample.json | jq -r 'select(.id?) | [.user.name, .retweet_count, .user.followers_count, .text] | @csv'
    
    
    "˗ˏˋ molly ˎˊ˗",0,176,"RT @Real_Liam_Payne: What a hero"
    "DerrickMadelyn",0,62,"Benefits upon hiring a calculator herein tampa differently rapt: xsLysp"
    "LemanLogan",0,67,"Do the improve on hood provision rates into the friendly desideratum.: FxzCOjcA"
    "larron prayer-uh♑️",0,696,"Last summer was definitely the best one I've had"
    "Joel Garza",0,102,"@ewa_jodlowska @dougnap 
    Gah! We were going to ask about those yesterday. The PyCon Mexico organizers wanted to take one."
    "BrianEmma",0,44,"However on prize lone in relation with the immeasurably fructuous electronic flageolet: fsnFMQR"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 2015-10-31
      • 2021-07-23
      • 2018-02-11
      • 2013-06-17
      • 2014-05-18
      相关资源
      最近更新 更多