简体   繁体   English

如何使用python将具有不同列的TXT文件转换为带有定界符“,”的文件a?

[英]How to convert TXT file with various columns to file a with delimiter “,” using python?

I have the following ORIGINAL .TXT file: 我有以下原始 .TXT文件:

"TRACE: A"
"FORMAT: WOW"

"Frequency" "Data 1"    "Data 2"
1   1   2
1   6   0

"Frequency" "Data 1"    "Data 2"
1   5   0
1   6   0

In order to run python script, I have to first open .TXT file in LibreOffice, then save and close it, to create EXPECTED .TXT file with a delimiter=',', as shown below: 为了运行python脚本,我必须首先在LibreOffice中打开.TXT文件,然后保存并关闭它,以分隔符=','创建EXPECTED .TXT文件,如下所示:

"TRACE: A",,
"FORMAT: WOW",,
,,
"Frequency","Data 1","Data 2"
1,5,0
1,5,0

"Frequency","Data 1","Data Trace Imag"
1,5,0
1,5,0

Now I can use the following code to plot the graphs: 现在,我可以使用以下代码绘制图形:

import numpy as np
from pylab import *

fileName = 'EXPECTED.TXT';

traceAdata= np.genfromtxt(fileName, delimiter=',')[3:5].T;

x = traceAdata[0]*1e-6;
A = traceAdata[1];

plot(x,A);
savefig(fileName + '.png');

I have tried to use different delimiters in the original TXT file such as: ' ', None, '\\t', but none of them worked, and I had following error: 我试图在原始TXT文件中使用不同的定界符,例如:'',None,'\\ t',但它们都不起作用,并且出现以下错误:

Line #5 (got 3 columns instead of 1)

Is there any other way to convert original TXT file to the file with needed delimiter using python? 还有其他方法可以使用python将原始TXT文件转换为具有所需定界符的文件吗?

UPD: Current Solution, thank you @lxop. UPD:当前解决方案,谢谢@lxop。

import numpy as np
from pylab import *

fileName = 'C2.TXT';

traceAdata= np.genfromtxt(fileName, skip_header=21,skip_footer = 334).T;

x = traceAdata[0]*1e-6;
A = traceAdata[1];

plot(x,A);
savefig('traceAdata.png');

traceBdata= np.genfromtxt(fileName, skip_header=337).T;
x = traceBdata[0]*1e-6;
B = traceBdata[1];

plot(x,B);
savefig('traceBdata.png');

You can load the space separated file directly, without converting, with a script like 您可以使用类似以下的脚本直接加载以空格分隔的文件,而无需进行转换

import numpy as np
from pylab import *

fileName = '11.TXT';

traceAdata= np.genfromtxt(fileName, skip_header=4).T;

x = traceAdata[0]*1e-6;
A = traceAdata[1];

plot(x,A);
savefig(fileName + '.png');

In particular not the use of skip_header to skip over the lines that don't have data. 特别是不要使用skip_header跳过没有数据的行。 Also, if you explicitly specify delimiter=' ' then genfromtxt will treat each space as a delimiter and try to get values between the individual space characters, so just leave that argument out. 另外,如果您明确指定delimiter=' '那么genfromtxt会将每个空格视为一个分隔符,并尝试获取各个空格字符之间的值,因此,只需忽略该参数即可。

If you really want to convert it to a CSV first, then you should look at a parsing library, since it will need to handle quoting etc. 如果您真的想先将其转换为CSV,则应查看解析库,因为它需要处理引用等。

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

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