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

标签 python csv formatting twitter

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

关于python - 在 csv 文件中使用 python 格式化从 twitter api 返回的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10434669/

相关文章:

python - 跨 Django 项目对用户进行身份验证 - 从哪里开始?

python - 一次将所有打开的 matplotlib 图形保存在一个文件中

python - 会思考的 python

python - Pandas 按范围合并间隔

python3 (nltk/numpy/等) : ISO efficient way to compute find pairs of similar strings

php - SELECT...IN ($csv) 还是遍历数组更好?

python - 如何使用 python 将此 XML 文件转换为 CSV?

python - 在 python3 中写入 csv 中的 io.BytesIO 失败

javascript - 在 Javascript 中解析 ISO 8601 日期

c++ - C++ 格式化输出