如何使用Python将JSON(Twitter数据)转换为CSV

时间:2012-02-22 03:26:42

标签: python json twitter csv

我正在尝试查询twitter搜索引擎(search.twitter.com),将结果转换为json,然后将结果准备为研究项目的csv。我是一个python新手,但我已经设法自己编写程序的2/3。但是,我很难将我的json文件转换为csv格式。我尝试了各种建议的技术但没有成功。我在这里做错了什么?

这是我到目前为止所做的:

import twitter, os, json, csv

qname = raw_input("Please enter the term(s) you wish to search for: ")
date = int(raw_input("Please enter today's date (no dashes or spaces): "))
nname = raw_input("Please enter a nickname for this query (no spaces): ")
q1 = raw_input("Would you like to set a custom directory? Enter Yes or No: ")

if q1 == 'No' or 'no' or 'n' or 'N':
    dirname = 'C:\Users\isaac\Desktop\TPOP'

elif q1 == 'Yes' or 'yes' or 'y' or 'Y':
    dirname = raw_input("Please enter the directory path:")

ready = raw_input("Are you ready to begin? Enter Yes or No: ")
while ready == 'Yes' or 'yes' or 'y' or 'Y':
    twitter_search = twitter.Twitter(domain = "search.Twitter.com")
search_results = []
for page in range (1,10):
    search_results.append(twitter_search.search(q=qname, rpp=1, page=page))
    ready1 = raw_input("Done! Are you ready to continue? Enter Yes or No: ")
    if ready1 == 'Yes' or 'yes' or 'y' or 'Y':
        break

ready3 = raw_input("Do you want to save output as a file? Enter Yes or No: ")
while ready3 == 'Yes' or 'yes' or 'y' or 'Y':
    os.chdir(dirname)
    filename = 'results.%s.%06d.json' %(nname,date)
    t = open (filename, 'wb+')
    s = json.dumps(search_results, sort_keys=True, indent=2)
    print >> t,s
    t.close()
    ready4 = raw_input("Done! Are you ready to continue? Enter Yes or No: ")
    if ready4 == 'Yes' or 'yes' or 'y' or 'Y':
        break

ready5 = raw_input("Do you want to save output as a csv/excel file? Enter Yes or No: ")
while ready5 == 'Yes' or 'yes' or 'y' or 'Y':
    filename2 = 'results.%s.%06d.csv' %(nname,date)
    z = json.dumps(search_results, sort_keys=True, indent=2)
    x=json.loads(z)

    json_string = z
    json_array = x

    columns = set()
    for entity in json_array:
        if entity == "created_at" or "from_user" or "from_user_id" or "from_user_name" or "geo" or "id" or "id_str" or "iso_language_code" or "text":
            columns.update(set(entity))

    writer = csv.writer(open(filename2, 'wb+'))
    writer.writerow(list(columns))
    for entity in json_array:
        row = []
        for c in columns:
            if c in entity: row.append(str(entity[c]))
            else: row.append('')

3 个答案:

答案 0 :(得分:1)

你有几个不同的问题。

首先,

的语法
x == 'a' or 'b' or 'c'

可能不会做你认为它做的事情。你应该使用

x in ('a', 'b', 'c')

代替。

其次,您的ready5变量永远不会更改,并且无法在循环中正常工作。尝试

while True:
    ready5 = raw_input("Do you want to save output as a csv/excel file? Enter Yes or No: ") 
    if ready5 not in (...):
        break

最后,您的转储/加载代码有问题。你从twitter得到的应该是一个JSON字符串。你的问题遗漏了一些代码,所以我无法确定,但我认为你根本不想使用json.dumps。您正在阅读 JSON(使用json.loads)和写入 CSV(使用csv.writer.writerow)。

答案 1 :(得分:0)

另一种方法是让tablib为您进行实际转换:

import tablib
data = tablib.Dataset()
data.json = search_results
filename = 'results.%s.%06d.csv' %(nname,date)
csv_file = open(filename, 'wb')
csv_file.write(data.csv)

答案 2 :(得分:0)

经过一番搜索后,我在这里找到了答案:http://michelleminkoff.com/2011/02/01/making-the-structured-usable-transform-json-into-a-csv/

代码看起来应该是这样的:(如果你正在搜索twitter python api)

filename2 = '/path/to/my/file.csv'
writer = csv.writer(open(filename2, 'w'))
z = json.dumps(search_results, sort_keys=True, indent=2)
parsed_json=json.loads(z)
#X needs to be the number of page you pulled less one. So 5 pages would be 4.
while n<X:
 for tweet in parsed_json[n]['results']:
     row = []
     row.append(str(tweet['from_user'].encode('utf-8')))
     row.append(str(tweet['created_at'].encode('utf-8')))
     row.append(str(tweet['text'].encode('utf-8')))
     writer.writerow(row)
 n = n +1

感谢大家的帮助!