【问题标题】:Searching for a string from a line number in both directions从行号双向搜索字符串
【发布时间】:2011-09-04 17:29:32
【问题描述】:

使用 Python 2.4,我正在读取一个大的平面文件并选择一个特定的行号。现在我想在该行号之前搜索一个字符串,例如START,在该行号之后搜索一个字符串END。

如何获取最近出现的字符串START(在当前行号之前)和END(在当前行号之后)的行号?

【问题讨论】:

    标签: python string search variables


    【解决方案1】:

    这个怎么样:

    line_no = 1
    
    # Seek the last START before reaching the target line.
    start_line_no = -1
    while line_no != target_line_no:
        line = input.readline()
        if line == "":
            # File is shorter than you think.
            break
        line_no += 1
        if START in line:
            start_line_no = line_no
    
    # Seek the first END after the target line.    
    end_line_no = -1
    while true:
        line = input.readline()
        if line == "":
            # END could not be found.
            break
        line_no += 1
        if END in line:
            end_line_no = line_no
            break
    
    print start_line_no, end_line_no
    

    【讨论】:

    • 感谢此代码。但是假设我正在使用一个非常大的文件,而我要查找的内容在文件的中间。从头开始搜索每一行不是很密集吗?有没有更有效的方法来做到这一点?
    • 先正确,再测量,再看是否需要优化。过早地根据你的猜测进行优化是低效的,这是万恶之源。
    • 如果行有任意长度,比没有,没有比这更有效的方法(除了为将来的操作预处理文件)。顺序文件访问是一种超快速的操作。在寻找棘手的优化之前,我会尝试这样做。
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多