打印两个重复词之间的行
之前的问题被重复了,因为没有找到完全相同的。这是一个不同的问题,我在网上找了很久也没找到答案!
我还是个新手,来这个网站就是为了找出这个问题的解决办法。我想要打印出文本文件中两个特定单词之间的某些行。
文本文件内容:
....
accounts
Bank
Credit
good value
money
Amount
Amount
我需要打印出“Credit”和“Amount”之间的行。问题是这里有两个“Amount”,所以我不知道该怎么解决。
期望的输出结果:
good value
money
请帮帮我!非常感谢你的回答!
代码:
import reresult = []
with open("acc.txt", "r") as f:
a = [x.rstrip() for x in f]
# store its index
for item in a:
if item.startswith("Credit"): # same as your re check
break
ind = a.index(item) #here it produces index no./line no.
result.extend(a[ind:])
if item.startswith("Amount"):
break
ind = a.index(item) #here it produces index no./line no.
result.extend(a[:ind])
for item in result:
print item
1 个回答
0
你可以试试下面的代码,
>>> import regex
>>> s = """accounts
... Bank
... Credit
... good value
... money
... Amount
... Amount"""
>>> m = regex.findall(r'(?s)(?<=Credit\s*\b).*?(?=Amount)', s)
>>> for i in m:
... print i
...
good value
money