将Tweety(python模块)搜索结果写入CSV

时间:2012-06-01 17:50:44

标签: python twitter csv

以下是我正在使用的简单代码:

import tweepy

result = tweepy.api.search(q="McDonalds ",rpp=1000,page=2, geocode= "34.085422,-117.900879,100mi" )

for tweet in result:
    print tweet.text
    print tweet.geo

它返回我想要的结果。在我的IDE中,我得到这样的结果:

@stevo_k14 I'm going back after mcdonalds haha

None

“@FunnyEvil: If bars can't serve drunk people, Mcdonalds shouldn't be able to serve fat people.”

{u'type': u'Point', u'coordinates': [33.9581, -118.1779]}

Mcdonalds for breakfast? Yup i think so :)

None

@JessicaCarrillo You make me want to go out to McDonalds right now!!!!! Lol good morning.

{u'type': u'Point', u'coordinates': [33.9443, -118.0038]}

有些人没有返回位置和一些返回位置。我真正想做的是将结果直接写入csv文件,其中Keyword,Tweet,Lat,Lon作为我的标题。在这种情况下,关键字将是“麦当劳”。如果有一些ifelse语句不写入结果,除非它们有位置,这也是很好的。

我是编程新手,所以非常感谢您的帮助!感谢

1 个答案:

答案 0 :(得分:1)

您可以使用csv模块并迭代现有的推文。

import tweepy
import csv

keyword = 'McDonalds '
result = tweepy.api.search(q=keyword,rpp=1000,page=2, geocode= "34.085422,-117.900879,100mi" )

with open('some.csv', 'w') as acsv:
    w = csv.writer(acsv)
    w.writerow(('Keyword', 'Tweet', 'Lat', 'Lon'))
    for tweet in result:
        lat, lon = tweet.geo if tweet.geo else ('', '')
        w.writerow((keyword, tweet.text, lat, lon))