【发布时间】:2018-04-26 09:17:22
【问题描述】:
请耐心等待,我无法包含我的 1,000+ 行程序,并且说明中有几个问题。
所以我正在寻找几种类型的模式:
#literally just a regular word
re.search("Word", arg)
#Varying complex pattern
re.search("[0-9]{2,6}-[0-9]{2}-[0-9]{1}", arg)
#Words with varying cases and the possibility of ending special characters
re.search("Supplier [Aa]ddress:?|Supplier [Ii]dentification:?|Supplier [Nn]ame:?", arg)
#I also use re.findall for the above patterns as well
re.findall("uses patterns above", arg
我总共有大约 75 个,其中一些需要移动到深度嵌套的函数中
我应该何时何地编译这些模式?
现在我正在尝试通过编译 main 中的所有内容来改进我的程序,然后将已编译 RegexObjects 的正确列表传递给使用它的函数。 这会提高我的表现吗?
执行以下操作会提高我的程序速度吗?
re.compile("pattern").search(arg)
编译后的模式是否保留在内存中,所以如果一个函数被多次调用,它会跳过编译部分吗?所以我不必在函数之间移动数据。
如果我移动数据这么多,是否值得编译所有模式?
有没有更好的方法来匹配没有正则表达式的常规单词?
我的代码的简短示例:
import re
def foo(arg, allWords):
#Does some things with arg, then puts the result into a variable,
# this function does not use allWords
data = arg #This is the manipulated version of arg
return(bar(data, allWords))
def bar(data, allWords):
if allWords[0].search(data) != None:
temp = data.split("word1", 1)[1]
return(temp)
elif allWords[1].search(data) != None:
temp = data.split("word2", 1)[1]
return(temp)
def main():
allWords = [re.compile(m) for m in ["word1", "word2", "word3"]]
arg = "This is a very long string from a text document input, the provided patterns might not be word1 in this string but I need to check for them, and if they are there do some cool things word3"
#This loop runs a couple million times
# because it loops through a couple million text documents
while True:
data = foo(arg, allWords)
【问题讨论】:
-
如果每个模式都使用一次,编译它们是没有意义的。当您预编译并在循环中数千次使用这些模式时,您会看到速度提升,因为您每次都节省了预编译。
-
@cᴏʟᴅsᴘᴇᴇᴅ 每个模式我使用了几百万次
-
好,你的决定变得容易了!
-
re.compile(m) for m in ["word1", "word2", "word3"]为什么不re.compile("|".join(["word1", "word2", "word3"])所以你让“oring”到re(它更快) -
@Jean-FrançoisFabre 现在我知道我可以做到,我一定会使用它
标签: python regex python-2.7 performance