在Python Reverse Find in String中有一个向后内联搜索的解决方案| :
s.rfind('I', 0, index)
但是如果我需要在该行之上的几行中搜索一个字符串呢?假设我使用以下方法找到了关键字:
with open("file.txt") as f
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "keyword" in line:
do_something()
我要do_something()
是向后找另一个关键字。要应用上面的代码,我想我需要 f.read()
以便我可以将文件作为字符串。但这完全是疯了,因为我必须 readlines()
和 read()
(大)文件。我需要使用readlines()
,因为第一个关键字可能在文本中出现多次,我需要找到它们。
有没有更好的方法来做到这一点?
@engineer
- kỹ sư
@engineering
- kỹ thuật
- civil e. ngành xây dựng
- communication e. kỹ thuật thông tin
- control e. kỹ thuật [điều chỉnh, điều khiển] (tự động)
- development e. nghiên cứu những kết cấu mới
最佳答案
我宁愿这样处理:因为你想找到以 @
开头的行,我宁愿将所有行存储在一个列表中,如果有新的行则丢弃前面的行找到以 @
开头的行。
因此我们得到:
def do_something(lines):
print("I've got:")
print(''.join(lines))
lines = []
with open("file.txt") as f:
for i, line in enumerate(f):
if line.startswith('@'):
lines = []
lines.append(line)
if 'development' in line:
do_something(lines)
file.txt
的输出将是:
I've got:
@engineering
- kỹ thuật
- civil e. ngành xây dựng
- communication e. kỹ thuật thông tin
- control e. kỹ thuật [điều chỉnh, điều khiển] (tự động)
- development e. nghiên cứu những kết cấu mới
一般情况下,如果你只想得到 N
行,你可以使用 collections.deque
而不是列表:
from collections import deque
N = 100
last_lines = deque(maxlen=N)
with open("file.txt") as f:
for i, line in enumerate(f):
last_lines.append(line)
if 'development' in line:
do_something(last_lines)
现在 do_something
将被传递到最后 100 行,包括当前行,如果当前行包含单词 development
。
关于python - 如何在 Python 3 中向后搜索几行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32297315/