【问题标题】:Use Python to manipulate txt file presentation of key-value grouping使用Python操作键值分组的txt文件表示
【发布时间】:2011-11-24 07:54:32
【问题描述】:

我正在尝试使用 Python 来操作格式 A 的文本文件:

Key1  
Key1value1  
Key1value2  
Key1value3  
Key2  
Key2value1  
Key2value2  
Key2value3  
Key3... 

进入格式B:

Key1 Key1value1  
Key1 Key1value2  
Key1 Key1value3  
Key2 Key2value1  
Key2 Key2value2  
Key2 Key2value3  
Key3 Key3value1...

具体来说,这里是对文件本身的简要介绍(仅显示一个键,完整文件中还有数千个):

chr22:16287243: PASS  
patientID1  G/G  
patientID2  G/G  
patient ID3 G/G

这里是所需的输出:

chr22:16287243: PASS  patientID1    G/G  
chr22:16287243: PASS  patientID2    G/G  
chr22:16287243: PASS  patientID3    G/G

我编写了以下可以检测/显示键的代码,但是我无法编写代码来存储与每个键关联的值,然后打印这些键值对。谁能帮我完成这项任务?

import sys
import re

records=[]

with open('filepath', 'r') as infile:
    for line in infile:
        variant = re.search("\Achr\d",line, re.I) # all variants start with "chr"
        if variant:
            records.append(line.replace("\n",""))
            #parse lines until a new variant is encountered

for r in records:
    print (r)

【问题讨论】:

    标签: python text-files key-value


    【解决方案1】:

    一次性完成,不存储行:

    with open("input") as infile, open("ouptut", "w") as outfile:
        for line in infile:
            if line.startswith("chr"):
                key = line.strip()
            else:
                print >> outfile, key, line.rstrip("\n")
    

    此代码假定第一行包含一个键,否则将失败。

    【讨论】:

    • 我不得不稍微改变一下 print stmt 的格式,但现在效果很好!我也不知道“startswith”,所以也谢谢你:)
    【解决方案2】:

    首先,如果字符串以字符序列开头,请不要使用正则表达式。更简单、更易于阅读:

    if line.startswith("chr")
    

    下一步是使用一个非常简单的状态机。像这样:

    current_key = ""
    
    for line in file:
        if line.startswith("chr"):
            current_key = line.strip()
    
        else:
            print " ".join([current_key, line.strip()])
    

    【讨论】:

      【解决方案3】:

      如果每个键总是有相同数量的值,islice 很有用:

      from itertools import islice
      
      with open('input.txt') as fin, open('output.txt','w') as fout:
          for k in fin:
              for v in islice(fin,3):
                  fout.write(' '.join((k.strip(),v)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-12
        • 2019-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多