gpt4 book ai didi

python - 在 Python 中构建高效函数

转载 作者:行者123 更新时间:2023-11-28 19:55:02 26 4
gpt4 key购买 nike

我的编程几乎都是自学的,所以如果我的某些术语在这个问题中不适用,我提前道歉。另外,我将使用一个简单的示例来帮助说明我的问题,但请注意,示例本身并不重要,它只是希望让我的问题更清楚的一种方式。

假设我有一些格式不正确的文本,其中有很多我想要清理的额外空白。因此,我创建了一个函数,它将用单个换行符替换任何包含换行符的空白字符组,并将任何其他空白字符组替换为单个空格。该函数可能看起来像这样

def white_space_cleaner(text):
new_line_finder = re.compile(r"\s*\n\s*")
white_space_finder = re.compile(r"\s\s+")
text = new_line_finder.sub("\n", text)
text = white_space_finder.sub(" ", text)
return text

工作正常,问题是现在每次我调用函数时它都必须编译正则表达式。为了让它运行得更快,我可以这样重写它

new_line_finder = re.compile(r"\s*\n\s*")
white_space_finder = re.compile(r"\s\s+")
def white_space_cleaner(text):
text = new_line_finder.sub("\n", text)
text = white_space_finder.sub(" ", text)
return text

现在正则表达式只编译一次,函数运行速度更快。在这两个函数上使用 timeit 我发现第一个函数每个循环花费 27.3 µs,第二个函数每个循环花费 25.5 µs。一个小的加速,但如果该函数被调用数百万次或具有数百个模式而不是 2 个,则可能会很重要。当然,第二个函数的缺点是它污染了全局命名空间并降低了代码的可读性.是否有某种“Pythonic”方式可以在函数中包含一个对象(如已编译的正则表达式),而无需在每次调用该函数时都重新编译它?

最佳答案

保留要应用的元组列表(正则表达式和替换文本);似乎没有迫切需要为每个人单独命名。

finders = [
(re.compile(r"\s*\n\s*"), "\n"),
(re.compile(r"\s\s+"), " ")
]
def white_space_cleaner(text):
for finder, repl in finders:
text = finder.sub(repl, text)
return text

您还可以合并 functools.partial:

from functools import partial
replacers = {
r"\s*\n\s*": "\n",
r"\s\s+": " "
}
# Ugly boiler-plate, but the only thing you might need to modify
# is the dict above as your needs change.
replacers = [partial(re.compile(regex).sub, repl) for regex, repl in replacers.iteritems()]


def white_space_cleaner(text):
for replacer in replacers:
text = replacer(text)
return text

关于python - 在 Python 中构建高效函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31862738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com