我正在制作一个脚本来提取 cvs 文件中的信息。 每列由“;”分隔。 输出应该是包含我要提取的列的字符串列表。
我想用综合列表来做这个,我想做类似的事情:
[ c[1] for c as l.split(";") in for l in lines ]
如果您了解 Python,您会猜到它不起作用。 我怎么能实现这样的目标?
当然,我可以使用 [ l.split(";") for l in lines ] 但实际上我需要提取多个列,因此进行多次拆分不是正确的选择。
文件看起来像:
115239747;darwin;simone;simone@gmail.com;678954312
112658043;de beauvoir;charles;charles@laposte.net;745832259
115831259;ramanujan;godfrey;godfrey@etu.univ.fr;666443810
114873956;hardy;srinivasa;srini@hotmail.com;659332891
114823401;germain;marguerite;marg@etu.univ.fr;768532870
115821145;yourcenar;sophie;sophie@gmail.com;645388521
114560013;harendt;michel;micha@etu.univ.fr;666458200
115702831;foucault;hannah;ha@laposte.net;691337456
我想提取第二列和第三列。
编辑:我不想只使用 Python 语言功能(没有 cvs 库),因为它是针对 Python 的初学者类(class)。谢谢。
请您参考如下方法:
由于更新的问题更新了答案:
>>> import csv
>>> from operator import itemgetter
>>>
>>> cols = [1,2] # list all the columns you want here
>>> with open('testfile') as f:
... ig = itemgetter(*cols)
... result = [ig(row) for row in csv.reader(f, delimiter=';')]
...
>>> result
[('darwin', 'simone'), ('de beauvoir', 'charles'), ('ramanujan', 'godfrey'), ('hardy', 'srinivasa'), ('germain', 'marguerite'), ('yourcenar', 'sophie'), ('harendt', 'michel'), ('foucault', 'hannah')]
没有导入:
>>> cols = [1,2] # list all the columns you want here
>>> with open('testfile') as f:
... split_lines = [line.split(';') for line in f]
... result = [[line[col] for col in cols] for line in split_lines]
...
>>> result
[['darwin', 'simone'], ['de beauvoir', 'charles'], ['ramanujan', 'godfrey'], ['hardy', 'srinivasa'], ['germain', 'marguerite'], ['yourcenar', 'sophie'], ['harendt', 'michel'], ['foucault', 'hannah']]
