【发布时间】: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