我有一个包含某些规则的文本文件。这是格式:
: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])
print list1显示
[':abc_efg (\n\t\t\t', ': xxyyzz-x1y1-z1z2-z3z4 \n\t\t)\n\t\t']
答案 0 :(得分:0)
Use f.readline() to read a file line by line.
It 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()
答案 1 :(得分:0)
使用以下正则表达式,首先是高效,其次,如果用于大量解析,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'}
将正则表达式分成多行,以便清楚地看到它。