通过python检查标题将逐行文本文件转换为制表符分隔格式

2024-04-30 07:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个实验数据的大文本文件,比如

spectrum:
 index: 1
 mz: 4544.5445
 intensity: 57875100000
 type: 1
 something: skip
 params - m1
 binary: [4] 1 2 3 4 
 params - int1
 binary: [4] 11 22 33 44
spectrum:
 index: 2
 mz: 546.7777
 intensity: 210009
 type: 2
 params - m2
 binary: [4] 2 3 4 5 
 params - int2
 binary: [4] 55 44 33 22
 charge: 3
 others: no need to put into column
spectrum:
 index: 3

我想把它打印成csv文件,每个光谱数据中的信息都放在同一行关于它的标题。如果他们没有该标题中的信息,只需跳过(或放入NA)。如果它们有多个值,则打印下一行

python有没有一些简单的方法可以得到这样的结果? enter image description here


Tags: 数据信息标题indextypeparamssomethingspectrum
1条回答
网友
1楼 · 发布于 2024-04-30 07:16:40

你想要这样的东西:

伪码

class Spectrum():
    def add(self, text):
        column, value = text.split(' ')
        if column == 'index:'
            self._csv['index'] = int(value)
        elif column == 'mz:'
            self._csv['mz'] = float(value)
        ... an so on

spectrum = Spectrum()
with text file as in_file
  for line in in_file
     if line == 'spectrum:'
        if  in_spectrum
            spectrum.expand_to_csv()
            spectrum = Spectrum()
        in_spectrum = True
        continue

     spectrum.add(line) 

相关问题 更多 >