gpt4 book ai didi

python - 在 python 3 中匹配和替换多个字符串的有效方法?

转载 作者:行者123 更新时间:2023-11-30 22:35:34 28 4
gpt4 key购买 nike

我有多个(>30)已编译的正则表达式

regex_1 = re.compile(...)
regex_2 = re.compile(...)
#... define multiple regex's
regex_n = re.compile(...)

然后我有一个函数,它接受一个 text 并使用上面的每个正则表达式和 re.sub 方法替换其中的一些单词,如下所示

def sub_func(text):
text = re.sub(regex_1, "string_1", text)
# multiple subsitutions using all regex's ...
text = re.sub(regex_n, "string_n", text)

return text

问题:是否有更有效的方法来进行这些替换?

正则表达式无法从当前形式进行概括或简化。

我觉得每次为每个正则表达式重新分配 text 的值非常慢,因为该函数仅替换整个 text 中的一两个单词每次重新分配。另外,考虑到我必须对多个文档执行此操作,这会进一步减慢速度。

提前致谢!

最佳答案

在 Python 中重新分配值需要恒定的时间。与 C 等语言不同,变量更像是“名称标签”。因此,更改名称标签所指向的内容只需很少的时间。

如果它们是常量字符串,我会将它们收集到一个元组中:

regexes = (
(regex_1, 'string_1'),
(regex_2, 'string_2'),
(regex_3, 'string_3'),
...
)

然后在您的函数中,只需迭代列表即可:

def sub_func_2(text):
for regex, sub in regexes:
text = re.sub(regex, sub, text)
return text

但是,如果您的正则表达式实际上名为 regex_1regex_2 等,则它们可能应该直接定义在某种列表中。

另请注意,如果您要进行诸如 'cat' -> 'dog' 之类的替换,则 str.replace()方法可能会更简单(text = text.replace('cat', 'dog')),而且可能会更快。

<小时/>

如果您的字符串非常长,并且使用正则表达式从头开始重新制作它可能需要很长时间。 @Oliver Charlesworth's 的实现评论中提到的方法可能是:

# Instead of this:
regexes = (
('1(1)', '$1i'),
('2(2)(2)', '$1a$2'),
('(3)(3)3', '$1a$2')
)


# Merge the regexes:
regex = re.compile('(1(1))|(2(2)(2))|((3)(3)3)')
substitutions = (
'{1}i', '{1}a{2}', '{1}a{2}'
)

# Keep track of how many groups are in each alternative
group_nos = (1, 2, 2)

cumulative = [1]
for i in group_nos:
cumulative.append(cumulative[-1] + i + 1)
del i
cumulative = tuple(zip(substitutions, cumulative))

def _sub_func(match):
iter_ = iter(cumulative)
for sub, x in iter_:
if match.group(x) is not None:
return sub.format(*map(match.group, range(x, next(iter_)[1])))

def sub_func(text):
return re.sub(regex, _sub_func, text)

但是如果您需要替换重叠的文本,这种情况就会失败。

关于python - 在 python 3 中匹配和替换多个字符串的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44528197/

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