python - 如何在 Python 3 中向后搜索几行?

标签 python python-3.x find

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(),因为第一个关键字可能在文本中出现多次,我需要找到它们。

有没有更好的方法来做到这一点?

image description

@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/

相关文章:

python - 在python中写入csv文件时如何跳过一列

python - 有人知道使用 sqlite 库的 Python 开源 Web 应用程序吗?

python-3.x - tf.gradients() 是如何工作的?

python - 为什么在Python中使用Button函数时,文本参数响应循环而命令参数不响应

C# FindBySubjectName 函数

python - 对键也是字典的字典键进行排序

python - 以有限的优先级启动子进程

python - SSL:CERTIFICATE_VERIFY_FAILED 证书验证失败

c++ - STL 算法和 const_iterators

c# - 查找列表中最常出现的项目的方法