给定一个字符串和一个子字符串列表,这些子字符串应该被替换为占位符,例如
import re
from copy import copy
phrases = ["'s morgen", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
第一个目标是首先将original_text
中来自phrases
的子字符串替换为索引占位符,例如
[出来]:
Something, MWEPHRASE0, ik MWEPHRASE1 im das MWEPHRASE2 gehen
然后会有一些函数用占位符操作text
,例如
cleaned_text = func('Something, MWEPHRASE0, ik MWEPHRASE1 im das MWEPHRASE2 gehen')
print(cleaned_text)
结果是:
MWEPHRASE0 ik MWEPHRASE1 MWEPHRASE2
最后一步是以一种倒退的方式进行替换,并将原来的短语放回原处
' '.join([backplacement[tok] if tok in backplacement else tok for tok in clean_text.split()])
[出来]:
"'s_morgen ik 's-Hertogenbosch depository_financial_institution"
问题是:
phrases
中的子串列表很大,则第一次更换和最后一次背板的时间将非常长。在有没有办法用正则表达式进行更换/背板固定?
re.sub(r"{}".format(phrase), "MWEPHRASE{}".format(i), text)
正则表达式替换不是很有帮助,特别是如果短语中有子字符串与完整单词不匹配例如
phrases = ["org", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
backplacement = {}
text = copy(original_text)
for i, phrase in enumerate(phrases):
backplacement["MWEPHRASE{}".format(i)] = phrase.replace(' ', '_')
text = re.sub(r"{}".format(phrase), "MWEPHRASE{}".format(i), text)
print(text)
我们得到了一个尴尬的结果:
^{9}$我试过使用'\b{}\b'.format(phrase)
,但这对带有标点符号的短语不起作用
phrases = ["'s morgen", "'s-Hertogenbosch", "depository financial institution"]
original_text = "Something, 's morgen, ik 's-Hertogenbosch im das depository financial institution gehen"
backplacement = {}
text = copy(original_text)
for i, phrase in enumerate(phrases):
backplacement["MWEPHRASE{}".format(i)] = phrase.replace(' ', '_')
text = re.sub(r"\b{}\b".format(phrase), "MWEPHRASE{}".format(i), text)
print(text)
[出来]:
Something, 's morgen, ik 's-Hertogenbosch im das MWEPHRASE2 gehen
对于re.sub
regex模式中的短语,是否存在一些表示单词边界的地方?
而不是使用re.sub公司你可以把它分开!在
以下是上例的变量值:
^{pr2}$如您所见,列表包含元组。它们包含两个值-
some string
和boolean
,表示它是文本还是被替换的值(True
当文本时)。 在得到替换列表之后,可以像示例一样修改它,检查它是否是文本值(if x[1] == True
)。 希望有帮助!在p.S.字符串格式如
f"some string here {some_variable_here}"
需要python3.6下面是一个你可以使用的策略:
我认为在这个任务中使用正则表达式有两个关键点:
使用自定义边界,捕捉它们,并将它们与短语一起替换回来。
使用函数在两个方向上处理替换匹配。
下面是一个使用这种方法的实现。我稍微修改了一下你的文字,重复其中一个短语。在
运行此操作将生成:
^{pr2}$相关问题 更多 >
编程相关推荐