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
text.count('\n',0,pos)获取行号.Python中的循环很慢.字符串搜索非常快.如果需要查找多个字符串,请使用正则表达式.
如果这还不够快,请使用外部程序grep.
| 归档时间: |
|
| 查看次数: |
10706 次 |
| 最近记录: |