使用 python 将数据转换为 CSV

convert data to CSV with python

我对 python 中的词典没有深入了解。但是,我有结构化文本数据 (ASCII),我想将其转换为 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,

以另一种顺序获取列留作 reader 的练习。