简体   繁体   English

如何将具有逗号分隔符的 CSV 文件转换为仅具有空格分隔符的 csv

[英]How to convert CSV file which having comma delimiter to csv with only space delimiter

I am trying to convert the the comma-separated csv file to space separate columns.我正在尝试将以逗号分隔的 csv 文件转换为空格分隔的列。 Please see the columns of input and output file to understand the motive.请参阅输入列和 output 文件以了解动机。

fILENAME ,sent_no ,   word ,POS ,lab,Slab
File_1 ,  sentence:1,  abc, NNP, B,NO   
                     fhj, PSP, O,O    
                     bmm ,NNP,B,NO   
                     vbn ,PSP, O,O    
                     vbn ,NN , B,NO   
                     vbn ,NNPC,B,NO  
                     . , Sym ,O,O  

I have written code我已经写了代码

import csv
filename1 = sys.argv[1]
filename2 = sys.argv[2] 

with open(filename1) as infile, open(filename2, 'w') as outfile:
    print(infile.read())
    outfile.write(infile.read().replace(",", " "))

after this statement print(infile.read()) values are在此语句之后print(infile.read())值是

",",F,i,l,e,n,a,m,e,",",S,e,n,t,e,n,c,e,_,n,u,m,",",W,o,r,d,",",P,O,S,",",M,E,N,T,_,L,a,b,e,l,",",S,I,N,G,L,E,_,M,E,N,T,I,O,N
0,",",f,i,l,e,_,1,",",s,e,n,t,e,n,c,e,:,1,",",a,िb,c,",",N,N,P",",B,",",N,O

You can read and write using pandas and the sep argument to specify the required separator:您可以使用 pandas 和sep参数来指定所需的分隔符进行读写:

input_df = pd.read_csv(filename1, sep=",")
input_df.to_csv(filename2, sep=" ", index=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM