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

时间:2018-06-25 16:31:54

标签: python regex python-3.x

我正在尝试替换两个列表文本:

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)

输出:

  

今天是星期五<月> 2018年1月

正确的输出:

  

今天是<日> <月> 2018年1月

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

2 个答案:

答案 0 :(得分:2)

由于您需要替换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

答案 1 :(得分:2)

您确实滥用了and运算符,建议您阅读这篇文章以了解您的错误:Using "and" and "or" operator with Python strings

您应该在第一个sub的结果上应用第二个replaces = daysRegex.sub("<day>", monthsRegex.sub("<month>", text)) ,如下所示:

session_result_1

然后您将获得正确的输出。