解析文本文件并分离字典中的数据

时间:2018-07-17 17:47:26

标签: python list parsing dictionary append

我在解析文本文件时遇到一种复杂的问题。

我需要什么:

  1. 通读文本文件。

  2. 如果一行匹配特定条件,请创建一个名为(条件1)的键

  3. 复制后面的行作为列表。该列表需要与键关联(条件1)

  4. 再次遇到这种情况时,请输入一个新密钥并复制下面的行,然后重复步骤3直到文件结尾

问题:我在给定键的列表中添加新项时遇到问题

示例文本输入文件:

A1 letters characters jgjgjg
A2 letters numbers fgdhdhd
D1 letters numbers haksjshs
condition1, dhdjfjf
K2 letters characters jgjgjg
J1 alphas numbers fgdhdhd
L1 letters numbers haksjshs
condition2, dhdjfjf
J1 alphas numbers fgdhdhd
D1 letters numbers haksjshs
J1 alphas numbers fgdhdhd
D1 letters numbers haksjshs

预期词典:

dictone = {'condition1':['K2 letters characters jgjgjg','J1 alphas numbers fgdhdhd','L1 letters numbers haksjshs'], 'condition2':['J1 alphas numbers fgdhdhd','D1 letters numbers haksjshs','J1 alphas numbers fgdhdhd','D1 letters numbers haksjshs'..........}

这是我到目前为止所做的。

flagInitial = False # flag to start copy after encountering condition

    with open(inputFilePath, "r") as tfile:

        for item in tfile:

            gcmatch = gcpattern.match(item)

            if gcmatch:

                extr = re.split(' ', item)
                laynum = extr[2]

                newKey = item[2:7] + laynum[:-1]
                flagInitial = True
                gcdict[newKey] = item
                continue

            if flagInitial == True:
                gcdict[newKey].append(item)  # stuck here 
                # print(gcdict[newKey])
                # print(newKey)

我缺少语法或其他内容吗?

2 个答案:

答案 0 :(得分:1)

尝试一下:

In [46]: from collections import defaultdict

In [47]: d = defaultdict(list)

In [48]: cond = None
    ...: for i in mystring.splitlines():
    ...:     if 'condition' in i.split()[0]:
    ...:         cond = i.split()[0][:-1]        ...:         
    ...:     elif cond:
    ...:         d[cond].append(i)


In [49]: d
Out[49]: 
defaultdict(list,
            {'condition1': ['K2 letters characters jgjgjg',
              'J1 alphas numbers fgdhdhd',
              'L1 letters numbers haksjshs'],
             'condition2': ['J1 alphas numbers fgdhdhd',
              'D1 letters numbers haksjshs',
              'J1 alphas numbers fgdhdhd',
              'D1 letters numbers haksjshs']})

答案 1 :(得分:1)

具有re.search函数和collection.defaultdict对象:

import re
import collections

with open('input.txt', 'rt') as f:
    pat = re.compile(r'^condition\d+')
    d = collections.defaultdict(list)
    curr_key = None

    for line in f:               
        m = pat.search(line)
        if m:
            curr_key = m.group()
            continue
        if curr_key:
            d[curr_key].append(line.strip())         

print(dict(d))        

输出:

{'condition1': ['K2 letters characters jgjgjg', 'J1 alphas numbers fgdhdhd', 'L1 letters numbers haksjshs'], 'condition2': ['J1 alphas numbers fgdhdhd', 'D1 letters numbers haksjshs', 'J1 alphas numbers fgdhdhd', 'D1 letters numbers haksjshs']}