Skip to main content
 首页 » 编程设计

python之在 csv 文件中使用 python 格式化从 twitter api 返回的数据

2025年05月04日9pander-it

问候各位爱好者!我正在做一个项目,我正在利用 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'] 

请您参考如下方法:

如果要生成 CSV 文件,请使用 the csv module !

例如:

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'])