大文本文件中最快的文本搜索方法

use*_*348 4 python google-app-engine

我正在一个相当大的txt文件中进行文本搜索(100k行,7mo)文本不是很大但我需要大量的搜索.我想查找目标字符串并返回它出现的行.格式化我的文本文件,以便目标只能出现在一行中.

什么是最有效的方式?我做了很多搜索,所以我想提高速度.这是我现在的代码:

def lookup_line(target):
    #returns line of the target, or None if doesnt exist
    line=None
    dir=os.path.dirname(__file__)
    path=dir+'/file.txt'
    file=open(path,'r')
    while line==None:
        l=file.readline()
        l=unicode(l,'utf-8')
        if target in l:
            break
        if l=='': break #happens at end of file, then stop loop
    line=l
    if line=='':line=None #end of file, nothing has been found
    file.close()
    return line
Run Code Online (Sandbox Code Playgroud)

我将这个python代码用于google Appengine应用程序.

谢谢!

Aar*_*lla 13

  1. 立即将整个文本加载到RAM中.不要逐行阅读.
  2. 在blob中搜索模式.如果找到它,请使用text.count('\n',0,pos)获取行号.
  3. 如果您不需要行号,请查找上一个和下一个EOL以删除文本中的行.

Python中的循环很慢.字符串搜索非常快.如果需要查找多个字符串,请使用正则表达式.

如果这还不够快,请使用外部程序grep.