如何将Twitter实时流数据保存到结构良好的CSV文件中

时间:2019-09-08 17:57:30

标签: csv dictionary duplicates tweepy sentiment-analysis

以下代码会将数据保存到csv文件中。

class listener(StreamListener):
    def on_data(self,data):
        try:
            tweet = json.loads(data)
            print (tweet['text'])
            dictionary={}
            dictionary['tweet'] = tweet['text']
            dictionary['id'] = tweet['id']

            json_data = json.dumps(dictionary)

            saveFile = open('LiveTweetFeed.csv','a')
            saveFile.write(json_data)
            saveFile.write('\n')
            saveFile.close()
            return True

但是结果并不像我预期的那样结构化。 看起来像这样

  

'{“ tweet”:“我看见一个警察过去了,就像我要在手机上看到我一样。...然后我意识到我正坐在星巴克\ u2026,” id “:1170735792022376448} \ n {” tweet“:” RT @brainwxrms:想象自己是一个女孩,不得不在你的车子里多留一条内衣,以防万一某个家伙在2026年把卡车翻了个身,“,” id“ :1170735792416858114} \ n {“ tweet”:“ RT @Im_TweetinKid:这绝对是一辆小鸡车,” id“:1170735793402302464} \ n {” tweet“:” RT @monicafraga:Bom dia,meu povo,menos pro estagi \ u00e1rio mau car \ u00e1ter do G1。\ n#EuConfioEmBolsonaro“,” id“:1170735793528279046} \ n {” tweet“:” \ ud83d \ udcfa As \ u00ed es el衣领m \ u00e1s caro del mundo。... ..“,” id“:1170735793931005953} \ n {” tweet“:” RT @lemondefr:\ u00ab看不见的辅助点,倒向世界各地,再往下倒, 。Ils aident leur proche p \ u2026“,” id“:1170735794086207490} \ n {” tweet“:”汽车只是通过听\ u201c开车而没有我\ e我的,彻底改变了我今天的心情”,“ id”:1170735794656546816} \ n {“ tweet”:“ RT @ShuntaeS_:没有人:\ n \

为什么在每个tweet中都重复使用tweet这个名字?如果我正确理解,字典中将不会有任何重复的值。那为什么会这样呢?有人可以在这里解释我在做什么错。我希望以这种格式输出

>     id    tweet
>     045   when a father is dysfunctional and is so sel...
>     126   thanks for #lyft credit i can t use cause th...
>     287   bihday your majesty
>     315   #model i love u take with u all the time in ...
>     417   factsguide society now #motivation

预先感谢

0 个答案:

没有答案