如何使用Python将JSON(Twitter数据)转换为CSV
我试图查询twitter搜索引擎(search.twitter.com),将结果转换为json,然后将结果准备为csv用于研究项目。我是一名Python新手,但我已经设法自己编写2/3的程序。但是,我很难将我的json文件转换为csv格式。我尝试了各种建议的技术,但没有成功。我在这里做错了什么?如何使用Python将JSON(Twitter数据)转换为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('')
一些周围搜索后,我发现这里的答案: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
感谢大家的帮助!
你必须要在几个不同的问题。
首先,中
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
)。
谢谢大家的意见!我会尝试对代码进行这些更改。我实际上把其余的代码放在了你的头上。我在网上看到的大部分示例都提示了读取json/write csv组合的一些变体。我希望有一个csv文档,其中包含来自推文搜索的所有基本信息(即用户标识,大地水准面,ISO代码,文本等)。如果我只是做一个通用的转储,格式似乎都搞砸了。 – wsisaac 2012-02-22 12:25:32
一种不同的方法将有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)
这是否处理嵌套的数据? – 2013-04-28 16:46:06
看起来不是,它默默地写垃圾(提交一个bug:https://github.com/kennethreitz/tablib/issues/100)。但是你可以通过遍历第一维并编写多个“Databooks”来调整它以处理三维。 – 2013-04-28 23:01:25
有一个更好的解决方案(我不记得引用),它利用了一些递归。这是我的更新后的帖子的链接:http://theoryno3.blogspot.com/2013/04/how-to-convert-json-to-csv-in-python.html – 2013-04-29 20:24:08
你看到了什么问题? – 2012-02-22 03:38:37
“将结果转换为json,然后将结果准备为csv”应该如何工作? – 2012-02-22 03:39:01
你想要输出看起来像什么? “key1:value1,key2:value2,..”或“key1,key2,key3 ... \ n value1,value2,value3,...”(如由换行符分隔的列标题) – platinummonkey 2012-02-22 03:41:31