【问题标题】:Replace lists in text with python regex用 python 正则表达式替换文本中的列表
【发布时间】:2018-12-04 07:13:15
【问题描述】:

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

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)

输出:

今天是星期五 1 2018

正确的输出:

今天是 1 2018

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

【问题讨论】:

标签: python regex python-3.x


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    你会得到正确的输出。

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2017-10-18
      • 2014-03-11
      • 2014-05-12
      • 2011-04-29
      • 2023-01-11
      • 2012-06-17
      相关资源
      最近更新 更多