如何在Python 3中向后搜索几行?
How to search backward several lines in Python 3?
在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)
现在,如果当前行包含单词 development
.
,则 do_something
将被传递到包括当前行在内的最后 100 行
在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)
现在,如果当前行包含单词 development
.
do_something
将被传递到包括当前行在内的最后 100 行