我有一个包含四列的Excel电子表格(保存为csv文件)。第一列和第三列包含单词,第二列和第四列包含频率。所以它看起来像这样:
word1, freq1, word2, freq2
word3, freq3, word4, freq4
......等等
我有以下代码将csv转换为json文件。
import csv
import json
csvfile = open('sample.csv', 'r')
jsonfile = open('sample.json', 'w')
fieldnames = ("feature","r", "feature","r")
reader = csv.DictReader(csvfile, fieldnames)
out = json.dumps( [ row for row in reader ] )
jsonfile.write(out)
真的很简单。 但是,这会返回一个看起来像这样的json文件
[{"r" : freq2 "feature" : "word2"} {"r" : freq1 "feature" : "word1"}{"r" : freq4 "feature" : "word4"}{"r" : freq3 "feature" : "word3"}]
我正试图找出一种方法,以便返回的json文件看起来像这样
[{"word1" : freq1}{"word2" :freq2}{"word3" :freq3}{"word4" :freq4}]
换句话说,我想将我的电子表格的第一列作为第2列的键,将第3列作为第4列的键。
答案 0 :(得分:0)
不幸的是,python的DictReader并不适合你的用例,但是一点zip
魔术应该可以解决这个问题。
import csv, json
csvfile = open('sample.csv', 'r')
jsonfile = open('sample.json', 'w')
fieldnames = ("word1","freq1", "word2","freq2")
reader = csv.reader(csvfile, fieldnames)
out = json.dumps( [ dict(zip(row[::2], row[1::2])) for row in reader ] )
jsonfile.write(out)
dict(zip(row[::2], row[1::2]))
创建一个字典,从奇数列映射到一行的相应偶数列。
答案 1 :(得分:0)
稍微有点罗嗦,但你可以尝试一下吗?
import csv, json
def dump_to_json():
csv_result = []
with open('sample.csv', 'rb') as csvfile:
for row in csv.DictReader(csvfile, delimiter=',', quotechar='"'):
csv_result.append({'word1': row['word1'], 'freq1': row['freq1'],
'word2': row['word2'], 'freq2': row['freq2']})
json_feed = [{c['word1']: c['freq1'], c['word2']: c['freq2']} for c in csv_result]
with open('sample.json', 'w') as outfile:
json.dump(json_feed, outfile)
dump_to_json()
答案 2 :(得分:0)
假设你有这样的数据:
feature, r, feature, r
word1, freq1, word2, freq2
word3, freq3, word4, freq4
如果允许我使用自己的库,这是一个说明的解决方案:
>>> import pyexcel
>>> r=pyexcel.SeriesReader("sample.csv")
>>> r[0]
['word1', ' freq1', ' word2', ' freq2']
>>> r[1]
['word3', ' freq3', ' word4', ' freq4']
>>> r.series()
['feature', ' r', ' feature', ' r']
>>> r.column_at(0)
['word1', 'word3']
>>> r.column_at(1)
[' freq1', ' freq3']
>>> r.column_at(2)
[' word2', ' word4']
>>> r.column_at(3)
[' freq2', ' freq4']
>>> a=zip(r.column_at(0),r.column_at(1))
>>> b=zip(r.column_at(2),r.column_at(3))
>>> a+b
[('word1', ' freq1'), ('word3', ' freq3'), (' word2', ' freq2'), (' word4', ' freq4')]
>>> j=open('sample.json', 'w')
>>> import json
>>> j.write(json.dumps(a+b))
>>> j.close()
>>> exit()
结果如下:
[["word1", " freq1"], ["word3", " freq3"], [" word2", " freq2"], [" word4", " freq4"]]
如您所见,引号中还留有空格。所以你可以做的是使用SheetFormatter:
>>> import pyexcel
>>> r=pyexcel.SeriesReader("sample.csv")
>>> def clean(value, type):
... return value.strip()
...
>>> r.add_formatter(pyexcel.formatters.SheetFormatter(str, clean))
>>> r.column_at(0)
['word1', 'word3']
>>> r.column_at(1)
['freq1', 'freq3']
>>> r.column_at(2)
['word2', 'word4']
>>> r.column_at(3)
['freq2', 'freq4']
更多文档是on pyhosted
答案 3 :(得分:0)
尝试使用https://github.com/samarjeet27/CSV-Mapper/
import csvmapper
# create map file
mapper = csvmapper.DictMapper([
[
{'name':'word1' },
{'name':'word2'},
{'name':'word3'},
{'name':'word4'},
]
])
# parser instance
parser = csvmapper.CSVParser('sample.csv', mapper)
converter = csvmapper.JSONConverter(parser)
# conver to json
print converter.doConvert(False)
答案 4 :(得分:0)
没有导入的解决方案在PYTHON中将CSV转换为JSON 。
我确定json和csv库运行良好,但我最终没有它们。所以也许这对其他人来说可能很方便。
简而言之:这将从CSV中提取数据并构建JSON字符串。
笨拙,但有效。
#set up paths and vars
csvfile = open('input.csv','r')
jsonfile = open('output.json', 'w')
arr=[]
headers = []
# Read in the headers/first row
for header in csvfile.readline().split(','):
headers.append(header)
# Extract the information into the "xx" : "yy" format.
for line in csvfile.readlines():
lineStr = ''
for i,item in enumerate(line.split(',')):
if i < 28: #I skip the last two columns for my application
lineStr+='"'+headers[i] +'" : "' + item + '",\n'
arr.append(lineStr)
csvfile.close()
#convert the array into a JSON string:
jsn = '{\n "entries":['
jsnEnd = ']\n}'
for i in range(len(arr)-1):
if i == len(arr)-2:
jsn+="{"+str(arr[i])[:-2]+"}\n" #Get rid of the last comma if last entry
else:
jsn+="{"+str(arr[i])[:-2]+"},\n" #Get rid of the last comma
jsn+=jsnEnd
#write to file
jsonfile.write(jsn)
jsonfile.close()
print "Done."
将其更多地添加为其他可能需要这样的脚本的人的参考。