Skip to content Skip to sidebar Skip to footer

Parsing Text File And Segregating The Data In A Dictionary

I have a kind of complex problem here in parsing a text file. What I need: Read through a text file. If a line matches a specific condition, create a key named (condition 1) Cop

Solution 1:

Try this:

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']})

Solution 2:

With re.search function and collection.defaultdict object:

import re
import collections

withopen('input.txt', 'rt') as f:
    pat = re.compile(r'^condition\d+')
    d = collections.defaultdict(list)
    curr_key = Nonefor line in f:               
        m = pat.search(line)
        if m:
            curr_key = m.group()
            continueif curr_key:
            d[curr_key].append(line.strip())         

print(dict(d))        

The output:

{'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']}

Post a Comment for "Parsing Text File And Segregating The Data In A Dictionary"