[英]csv into multiple columns using split function using python
I am trying to split a specific column of csv into multiple column and then appending the split values at the end of each row. 我试图将csv的特定列拆分为多列,然后将拆分值附加在每行的末尾。
I wanted to split second column on ',' and '.' 我想在','和'。上分开第二列。 and ';' 和';' and then append to each row respective values. 然后将相应的值附加到每一行。
import csv fOpen1=open('Meta_D1.txt') reader=csv.reader(fOpen1) mylist=[elem[1].split(',') for elem in reader] mylist1=[] for elem in mylist: mylist1.append(elem) #writing to a csv file with open('out1.csv', 'wb') as fp: myf = csv.writer(fp, delimiter=',') myf.writerows(mylist1)
Can someone guide me further? 有人可以指导我吗?
To split with multiple delimiters, you can use regex
: 要使用多个分隔符进行拆分,可以使用regex
:
import re
re.split(';|, |\. ', col_2)
Example from your file: 文件中的示例:
>>> col_2 = "Braund, Mr. Owen Harris;22"
>>> re.split(';|, |\. ', col_2)
['Braund', 'Mr', 'Owen Harris', '22']
Using this, try the following to achieve your desired output: 使用此方法,请尝试以下操作以实现所需的输出:
import csv
import re
with open('out1.csv', 'wb') as fp:
with open('Meta_D1.txt', 'r') as f:
reader = csv.reader(f)
next(reader)
for line in reader:
cols = re.split(';|, |\. ', line[1])
del line[1]
line.extend(cols)
myf = csv.writer(fp, delimiter=',')
myf.writerow(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.