Python 匹配图案并打印下一行
我有一个包含某些规则的文本文件。以下是它的格式:Python 匹配图案并打印下一行,python,pattern-matching,generator,regex-lookarounds,Python,Pattern Matching,Generator,Regex Lookarounds,我有一个包含某些规则的文本文件。以下是它的格式: :SchoolName (rule_1) ) :xyz (true) :abc_efg ( : xxyyzz-x1y1-z1z2-z3z4 ) 我想匹配“:abc_efg”,并在匹配后获得行,即。 “:xxyyzz-x1y1-z1z2-z3z4” 每次有新文件时,它都会查找“:abc_efg”,并在匹配后获得相应的行 到目前为止我已经试过了 :SchoolName (rule_1) ) :xyz (true) :abc_efg (
:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
: xxyyzz-x1y1-z1z2-z3z4
)
:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
: xxyyzz-x1y1-z1z2-z3z4
)
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])
打印列表1显示
:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
: xxyyzz-x1y1-z1z2-z3z4
)
[':abc_efg (\n\t\t\t', ': xxyyzz-x1y1-z1z2-z3z4 \n\t\t)\n\t\t']
使用f.readline()逐行读取文件
:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
: xxyyzz-x1y1-z1z2-z3z4
)
当比赛进行时,它可以很容易地获得下一条线
:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
: xxyyzz-x1y1-z1z2-z3z4
)
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()
使用以下正则表达式,首先它是高效的,其次,如果用于繁重的解析,
str
方法会失控
:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
: xxyyzz-x1y1-z1z2-z3z4
)
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'}
重新导入
pat=re.compile(r):(\s+:\s(?P+?)\s\))
打开(somefile)作为fr:
match=pat.search(fr.read())
打印(match.groupdict())
Out[111]:{'x':'abc_efg','y':'xxyyz-x1y1-z1z2-z3z4'}
将正则表达式分成多行以清楚地看到它
:SchoolName (rule_1)
)
:xyz (true)
:abc_efg (
: xxyyzz-x1y1-z1z2-z3z4
)