【问题标题】:Read in record of multiple lines from file into nested dictionary in python将文件中的多行记录读入python中的嵌套字典
【发布时间】:2019-10-16 21:50:06
【问题描述】:

这是练习嵌套字典,或者字典数组,字典列表等。 数据结构可以最好地描述为 C/C++ 中的结构/类数组,每个结构都有多个成员。对我的挑战:
1)。每条记录的开头都有字符串“Sample Name”作为分隔符,后跟多个成员;
2)。每行记录的6个成员用冒号“:”分隔;
3)。如何将多行(而不是同一行的多个字段,这样更容易解析)读入记录的成员;
4)。 记录分隔符前面不能有空行。
我将样本输入和预期输出用于测试。
示例:input.txt

样品名称:CanNAM1_192 单核苷酸多态性:5392 MNP : 0 插入 : 248 删除:359 分阶段基因型:8.8% (2349/26565) MNP Het/Hom 比率 : - (0/0) 样品名称:CanNAM2_195 单核苷酸多态性:5107 MNP : 0 插入 : 224 删除:351 分阶段基因型:8.9% (2375/26560) MNP Het/Hom 比率 : - (0/0) 样品名称:CanNAM3_196 单核苷酸多态性:4926 MNP : 0 插入 : 202 删除:332 分阶段基因型:8.0% (2138/26582) MNP Het/Hom 比率 : - (0/0)

在 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


    【解决方案1】:
    data = {}
    with open("data.txt",'r') as fh:
        for line in fh.readlines(): #read in multiple lines
            if len(line.strip())==0:
                continue
    
            if line.startswith('Sample Name'):
                nameLine = line.strip()
                name = nameLine.split(": ")[1]
                data[name] = {}
            else:
                splitLine = line.split(":")
                variableName = splitLine[0].strip()
                value = splitLine[1].strip()
                data[name][variableName] = value
    
    print(data)
    
    1. 确保您正在阅读的行不为空。如果您从空行中删除所有空白空间,您将得到一个长度为零的字符串。我们只是检查一下。
    2. 如果行以Sample Name 开头,我们知道id 将出现在冒号和空格之后。我们可以按这些字符进行拆分。 id 将是分割线的第二部分,因此我们只需获取索引 1 处的项目。
    3. 在一个变量中跟踪当前 id(我称之为name)。为该 ID 创建一个空的嵌套字典条目。
    4. 如果该行不是 ID 行,则它必须是与最后输入的 ID 关联的数据行。
    5. 我们得到了这条线,用:分割它。变量的名称在左边,第一项,值在右边,所以是第二项。确保我们去掉两边所有多余的空格。
    6. 将变量和值对添加到 ID 的字典条目中。

    【讨论】:

    • 谢谢!我过度考虑了这个问题,因为 7 行作为单个记录 必须立即读入。还有一个问题,我的输入文件非常大(~30GB),readlines() 对它有好处吗?
    • 我认为你有比 readlines() 更大的问题。你有一台超过 30GB 内存的电脑吗?否则,计算机将无法将文件保存在内存中。我建议将您的数据文件分成可管理的块。不过,我不太确定 readlines() 与其他方法的性能。
    • 这就是为什么我多次调用 'next()' 函数希望读取一条记录的多行。
    【解决方案2】:

    在问题上花费了更多时间并得到了解决方案,这似乎 NOT “pythonic”,因为我的代码处理第一个“记录”(8 行数据,包括底部的空白行)是其余的都是多余的。

    import itertools
    data = {}
    with open("vcfstats.txt", 'r') as f:
        for line in f:
            if line.strip():                #Non blank line
                if line.startswith('Sample Name'):
                    nameLine = line.strip()
                    name = nameLine.split(": ")[1].strip()
                    data[name] = {}
                else:
                    splitLine = line.split(": ")
                    variableName = splitLine[0].strip()
                    values = splitLine[1].strip().split(" ")
                    data[name][variableName] = values[0]        #Only take the first item as value
            else:
                 continue
    
        for line in itertools.islice(f, 8):
            lines = (line.rstrip() for line in f)          # including blank lines
            lines = list(line for line in lines if line)   # skip blank lines
    
            for line in lines:
                if line.startswith('Sample Name'):
                    nameLine = line.strip()
                    name = nameLine.split(": ")[1].strip()
                    data[name] = {}
                else:
                    splitLine = line.split(": ")
                    variableName = splitLine[0].strip()
                    values = splitLine[1].strip().split(" ")
                    data[name][variableName] = values[0]        #Only take the first item as value
    

    我错过了什么?非常感谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      相关资源
      最近更新 更多