我有一个从互联网上获取信息的脚本。长话短说,我最终得到了一个包含字符串的变量。基于此字符串,我编写了脚本程序,以便根据以下方法决定是否丢弃或进一步处理字符串所涉及的信息:
我想知道什么是最好的算法是实现这一效率和一个良好的,如果不是100%正确的准确性。
目前,我有以下代码(大规模地简化为只包含特定的部分;通常会有循环围绕这个部分,等等):
#!/usr/bin/env python
import re
def findWord(z):
return re.compile(r'\b({0})\b'.format(z), flags=re.IGNORECASE).search
filterList = [
"term-1","term-2","term-n"
]
uncleanString = "This! is* a test [string],.}".lower()
#Remove all punctuation
for c in "!@#%&*()[]{}/?<>,.'":
cleanString = uncleanString.replace(c, "")
#Check if the words in filterList are present, if not then process further
no = 0
for word in filterList:
result = findWord(filterList[filterList.index(word)])(cleanString)
if result == None:
pass
else:
no = 1
break
if no == 0:
#then do further processing here, e.g.
print(cleanString)
#reset condition (when implementing code in loop(s)
no = 0在我的实际脚本中,我的filterList很大。这是一个缓慢的脚本,需要大约30分钟才能完成,不过我认为这更多是因为我正在运行它的平台(RPi而不是PyPy )、与internet的通信(BS4 4/HTTPlib)以及与MySQL数据库的交互……在我开始完善其他部分之前,你对我如何加快这部分的速度有什么想法吗?或者你会说上面的内容足够了吗?
发布于 2013-11-25 16:03:24
用交替的方法生成一个大型正则表达式。
reg=re.compile(r'\b('+"|".join(filterList)+r')\b')看上去像这样
\b(term-1|term-2|term-n)\b您不必遍历术语项,它们都在一个regexp中。
在编译后的对象上调用一次,而不是"findWord“调用
reg.search发布于 2013-11-25 15:51:12
当然,您可以提高它的可读性:
if not any(word in cleanString for word in filterList):
# further processing这将删除字符串格式设置和regex编译步骤。
https://stackoverflow.com/questions/20197017
复制相似问题