Align the pattern and print the following line

I have a text file containing specific rules. Here is the format for it:

:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
    : xxyyzz-x1y1-z1z2-z3z4
)
  • I want to combine for ': abc_efg' and get the line after the match ie ': xxyyzz-x1y1-z1z2-z3z4'
  • Each time there is a new file, it will search for ': abc_efg' and get the corresponding line after the match

So far i tried

with open('G:\CM\Python Exercises\Project_F\abc.txt') as f:
    text = f.read()
    list1=text.strip('\n\t').split(':')
    print list1
    for line in list1:
        if ':abc_efg' in list1:
            print line
            print '\n'.join(list1[i+1])

print list1 shows

[':abc_efg (\n\t\t\t', ': xxyyzz-x1y1-z1z2-z3z4 \n\t\t)\n\t\t']
+4
source share
2 answers

Use f.readline () to read the file line by line.

This makes it easy to get the next line when there is a match.

with open('abc.txt') as f:
    a = ' '
    while(a):
        a = f.readline()
        l = a.find(':abc_efg') #Gives a non-negative value when there is a match
        if ( l >= 0 ):
            print f.readline()
0
source

, -, , -, str - , .

import re
pat = re.compile(r":(?P<x>.+?)\s\(\s+:\s(?P<y>.+?)\s\)")
with open(somefile) as fr:
    match = pat.search(fr.read())
    print(match.groupdict())


Out[111]: {'x': 'abc_efg', 'y': 'xxyyzz-x1y1-z1z2-z3z4'}

, .

0

All Articles