gpt4 book ai didi

python - 使用 Python re 在一行中查找和分割

转载 作者:行者123 更新时间:2023-12-01 04:18:57 24 4
gpt4 key购买 nike

是否可以使用 re 模块在 Python 中的同一行中进行查找和替换?即还返回已替换的内容(与 re.subn 返回替换数量的方式类似)。

例如,我有 "FOO BAR PART 1" 形式的文本,我想要做的是将其转换为 "FOO BAR"“第 1 部分”

我能想到的就是使用类似的东西:

title_old = "FOO BAR PART 1"
parts_found = re.findall(r"PART [0-9]*$", title_old ) ## i.e. search for term
if parts_found != []:
part_string = parts_found[0]
title_new = re.sub(re.escape(parts_found[0]),"",title_old ) ## If that term exists, then substitute it.

最佳答案

您可以传递一个单独的方法而不是替换模式,并将匹配对象传递给该方法。您可以声明一个变量来跟踪所有替换的文本。

参见re.sub reference :

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

import re

replacements = []
def repl(m):
replacements.append(m.group(0)) # Add found match to the list
return ""; # We remove the match found

title_old = "FOO BAR PART 1"
print(re.sub(r"PART [0-9]*$", repl, title_old))
print(replacements)

参见demo

结果:

FOO 酒吧
['第 1 部分']

关于python - 使用 Python re 在一行中查找和分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962371/

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