我有一个制表符分隔的文本文件,每个记录有10列,如下所示:
p001 64 20141209 meals (attendees) ML ENTER Entertainment xyz Restaurants 6.0 "_e' Restaurants (123) 456-7890 \r\n FORUM \r\n ,Around \r\n\r\n':33 113-2 \r\n\r\n 8440 XYZ09'15 1:11PM \r\n\r\n 1 Burger 6.00 \r\n\r\n SSIONS 6.00 \r\n TOTAL PAID 6 .00 \r\n XXXXXXXXXXX2012 XX/XX \r\n XYZ EXPRESS
6.00 \r\n\r\n\r\n 7,-10( YOU! FOR DINING WITH US! \r\n\r\n 113-2 \r\n\r\nYour r is: 840 \r\n"
P.S:最后一栏的文字附在""中。我的第一栏并非独一无二。
我想将此文本文件转换为csv文件,以便我只从记录的第1,第2,第8,第9和第10列中选择数据。此外,所有数据都应包含在""。
中例如,上述记录应转换为输出csv文件中的以下行:
"p001","64","xyz Restaurants","6.0","_e' Restaurants (123) 456-7890 \r\n FORUM \r\n ,Around \r\n\r\n':33 113-2 \r\n\r\n 8440 XYZ09'15 1:11PM \r\n\r\n 1 Burger 6.00 \r\n\r\n SSIONS 6.00 \r\n TOTAL PAID 6 .00 \r\n XXXXXXXXXXX2012 XX/XX \r\n XYZ EXPRESS
6.00 \r\n\r\n\r\n 7,-10( YOU! FOR DINING WITH US! \r\n\r\n 113-2 \r\n\r\nYour r is: 840 \r\n"
答案 0 :(得分:2)
这对你有用。请注意,这会将csv库用于输入和输出,我们只需更改文本分隔符。在编写文件时,CSV应自动转义引号字符。
import csv
try:
with open(r'input.tsv', 'r', newline='\n') as in_f, \
open(r'output.csv', 'w', newline='\n') as out_f:
reader = csv.reader(in_f, delimiter='\t')
writer = csv.writer(out_f, delimiter=',', quoting=csv.QUOTE_ALL) # Quoting added per comment from @Rob.
for li in reader:
try:
writer.writerow([li[0], li[1], li[2], li[7], li[8], li[9],])
except IndexError: # Prevent errors on blank lines.
pass
except IOError as err:
print(err)
我无法解析样本数据中的标签位置(而不是空格),但使用input.tsv
的以下数据对其进行测试:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
将在output.csv
中生成以下结果:
"1","2","3","8","9","10"
"11","12","13","18","19","20"
"21","22","23","28","29","30"
请注意,添加quoting=csv.QUOTE_ALL
的代码中的更新是根据Rob的评论中的建议。谢谢你!#/ p>