我在优化这部分代码时遇到了一些麻烦。
它有效,但似乎不必要的慢。
该函数在searchString行中的文件中的line_nr之后搜索,并返回第一次匹配的行号。

import linecache
def searchStr(fileName, searchString, line_nr = 1, linesInFile):
# The above string is the input to this function
# line_nr is needed to search after certain lines.
# linesInFile is total number of lines in the file.

    while line_nr < linesInFile + 1:
        line = linecache.getline(fileName, line_nr)
        has_match = line.find(searchString)
        if has_match >= 0:
            return line_nr
            break
        line_nr += 1


我已经尝试过沿these行进行某些操作,但从未设法实现“从特定行号开始”输入。

编辑:用例。我正在对包含文本和数字的分析文件进行后期处理,这些文本和数字用标题分成不同的部分。 line_nr上的标头用于分解数据块以进行进一步处理。

通话示例:

startOnLine = searchStr(fileName,'Header 1',1,10000000):
endOnLine = searchStr(fileName,'Header 2',startOnLine,10000000):

最佳答案

为什么不从最简单的实现开始呢?

def search_file(filename, target, start_at = 0):
    with open(filename) as infile:
        for line_no, line in enumerate(infile):
            if line_no < start_at:
                continue
            if line.find(target) >= 0:
                return line_no
    return None

09-11 10:59