使用python将数据转换为CSV
问题描述:
我并没有深入参与Python中的字典。但是,我有结构化文本数据(ASCII),我想将其转换为CSV(输入数据库或电子表格)。并非所有值都可用于每行:使用python将数据转换为CSV
name Smith city Boston country USA
name Meier city Berlin ZIP 12345 country Germany
name Grigoriy country Russia
并非所有字段都在每行中。但是,字段值中不包含空格。我怎样才能在一个CSV的转换成文本文件一样
name, city, ZIP, country
Smith, Boston, , USA
Meier, Berlin, 12345, Germany
Grigory, , , Russia
答
试试这个:
d = """name Smith city Boston country USA
name Meier city Berlin ZIP 12345 country Germany
name Grigoriy country Russia"""
keys = {} # will collect all keys
objs = [] # will collect all lines
for line in d.split("\n"): # split input by linebreak
ks = [x for x in line.split()[::2]] # even positions: 0, 2, 4, 6
vs = [x for x in line.split()[1::2]] # odd positions: 1, 3, 5, 7
objs.append(dict(zip(ks, vs))) # turn line into dictionary
for key in ks:
keys[key] = True # note all keys
print(",".join(keys)) # print header row
for obj in objs:
print(",".join([obj.get(k, "") for k in keys]))
输出:
country,city,name,ZIP
USA,Boston,Smith,
Germany,Berlin,Meier,12345
Russia,,Grigoriy,
获得另一顺序列留作读者做练习。
你试过了什么? – 2015-02-11 19:39:54
尝试[csv模块](https://docs.python.org/2/library/csv.html)。 – 2015-02-11 19:44:55