我正在对一个相当大的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
我使用这段Python代码来开发Google App Engine应用程序。
谢谢!