【发布时间】:2019-10-16 21:50:06
【问题描述】:
这是练习嵌套字典,或者字典数组,字典列表等。
数据结构可以最好地描述为 C/C++ 中的结构/类数组,每个结构都有多个成员。对我的挑战:
1)。每条记录的开头都有字符串“Sample Name”作为分隔符,后跟多个成员;
2)。每行记录的6个成员用冒号“:”分隔;
3)。如何将多行(而不是同一行的多个字段,这样更容易解析)读入记录的成员;
4)。 记录分隔符前面不能有空行。
我将样本输入和预期输出用于测试。
示例:input.txt
在 awk 中有 RECORD 分隔符 RS 和 FIELD 分隔符 FS 可以在开始时设置,但据我所知,python 中没有这样的功能。
Output.tab:
CanNAM1_192 5392 0 248 359 8.8% - CanNAM2_195 5107 0 224 351 8.9% - CanNAM3_196 4926 0 202 332 8.0% -尝试为我的案例搜索一些示例代码,例如one,this one
import sys
filename=sys.argv[1]
Dictn = {}
with open(filename, 'r') as fh:
for line in fh:
while True:
if line.startswith('Sample Name'):
nameLine = line.strip()
ID = nameLine.split(':')
else:
line2 = next(fh).strip()
line2 = line2.split(':')
print (line2[0], line2[1]) # For debugging to see the parsing result
line3 = next(fh).strip().split(':')
line4 = next(fh).strip().split(':')
line5 = next(fh).strip().split(':')
line6 = next(fh).strip().split(':')
line7 = next(fh).strip().split(':')
Dictn.update({
ID[1]: {
line2[0]: line2[1],
line3[0]: line3[1],
line4[0]: line4[1],
line5[0]: line5[1],
line6[0]: line6[1],
line7[0]: line7[1],
}
})
break
print(Dictn)
Dictn.get('CanNAM1_192')
# {CanNAM1_192:{ {'SNPs' : '5392'}, {'MNPs' : '0'}, {'Insertions' : '248'}, {'Deletions' : '359'}, {'Phased Genotypes' : '8.8%'}, {'MNP Het/Hom ratio' : '-'} }}
我坚持通过一次读取 7 行来解析每条记录,然后将记录推送/更新到字典中。不擅长 Python,非常感谢任何帮助!
【问题讨论】:
标签: python dictionary nested