用python正则表达式替换文本中的列表

2024-06-26 01:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将两个列表替换为一个文本:

text = "today is friday july 1 2018"

days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
daysRegex = re.compile('|'.join(map(re.escape, days)))

months =  ['january', 'february', 'march', 'april', 'may', 'mai', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
monthsRegex = re.compile('|'.join(map(re.escape, months)))

replaces = daysRegex.sub("<day>", text) and monthsRegex.sub("<month>", text) 

print(replaces)

输出:

today is friday < month> 1 2018

正确输出:

today is < day> < month> 1 2018

我不确定是否正确使用了运算符。我只是想把我所学的付诸实践(但我可能误解了)


Tags: textremaptodayisdaysjulyjoin
2条回答

你确实误用了and操作符,我建议你阅读这篇文章来理解你的错误:Using "and" and "or" operator with Python strings

您应该对第一个结果应用第二个sub,如下所示:

replaces = daysRegex.sub("<day>", monthsRegex.sub("<month>", text))

你会得到正确的输出

因为你需要替换2的值,你可以做

演示:

import re
text = "today is friday july 1 2018"

days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
daysRegex = re.compile('|'.join(map(re.escape, days)))
months =  ['january', 'february', 'march', 'april', 'may', 'mai', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
monthsRegex = re.compile('|'.join(map(re.escape, months)))
replaces = daysRegex.sub("<day>", monthsRegex.sub("<month>", text))

print(replaces)

text = monthsRegex.sub("<month>", text)
replaces = daysRegex.sub("<day>", text)
print(replaces)

输出:

today is <day> <month> 1 2018

相关问题 更多 >