欢迎各位爱好者!我正在研究一个项目,我正在利用python与twitter api进行交互。
目标:将您在“pprint.pprint(datares)”中看到的原始数据中的原始数据的位置,推文文本和用户ID提取到csv文件中的指定格式。
问题:如何获取我返回到csv文件的信息,以便文件中的每一行显示如下:
行:推文文本,位置,创建者,用户ID
以下是我的代码,显示了到目前为止我能够返回的内容。
import urllib2, json, pprint, codecs, unicodedata
u = urllib2.urlopen('http://search.twitter.com/search.json?geocode=29.762778,-95.383056,25.0mi&page=1&rpp=20')
datares = json.load(u)
##raw data returned
pprint.pprint(datares)
##open csv file
with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='replace') as cache:
##need to save tweets,date,area,id to file
for tweet in datares['results']:
print tweet['text']
archive=tweet['text']
unicodedata.normalize('NFKD', archive).encode('ascii','ignore')
cache.write(archive)
for date in datares['results']:
print date['created_at']
for area in datares['results']:
print area['location']
for id in datares['results']:
print id['from_user']
答案 0 :(得分:1)
如果您想制作CSV文件,请使用the csv
module!
E.g:
with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='replace') as cache:
writer = csv.writer(cache)
for tweet in datares['results']:
writer.writerow([tweet['text'], tweet['area'], tweet['date'], tweet['id']])
或者:
with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='replace') as cache:
writer = csv.DictWriter(cache, ["text", "area", "date", "id"])
for tweet in datares['results']:
writer.writerow(tweet)
显然,你也可以使用writerows()
来进一步简化:
with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='replace') as cache:
writer = csv.DictWriter(cache, ["text", "area", "date", "id"])
writer.writerows(datares['results'])