【问题标题】:Python RegEx to replace stringPython RegEx 替换字符串
【发布时间】:2017-02-05 12:43:09
【问题描述】:

如何使用 RegEx(或 Python 中的其他内容)来满足以下要求? 我需要:

  1. 删除“梦想”一词(包括其所有词干)
  2. 删除所有之前的单词(即“dream”这个词后面的所有单词)
  3. 删除旁边的单词(在它前面/“梦想”的右侧)
  4. 从所有短语中删除“to”一词。

输入:

text = ["Dream of a car",
        "Dream to live in a world",
        "Dream about 8am every morning",
        "stopped dreaming today",
        "still dreaming of a car",
        "One more dream to come late tomorrow",
        "Dream coming to hope tomorrow"]

所需输出:

["a car",
 "live in a world",
 "8am every morning",
 " ",
 "a car",
 "come late tomorrow",
 "hope tomorrow"]

我试过了:

result = [re.sub('Dream', '', a) for a in text]

# MyOutput
[' of a car', ' to live in a world', ' about 8am every morning', 'stopped dreaming today', 'still dreaming of a car', 'One more dream to come late tomorrow', ' coming to hope tomorrow']

【问题讨论】:

  • 您提出的解决方案只能完成您的第一个要求的一半,甚至没有尝试解决其余部分。
  • 是的,我不知道如何去做剩下的事情 :(
  • 另外,您声称的输出与您的输入不匹配。
  • 是的,这是另一个谜,即使我在整个输入上运行它。
  • 不,我的意思是你声称你的尝试所做的并不是它实际所做的,因此不是minimal reproducible example

标签: python regex string list replace


【解决方案1】:

这给出了你需要的输出

result = [re.sub(r'\bto\b *', '', re.sub(r'^.*Dream[^ ]* *[^ ]* *', '', a, flags=re.I)) for a in text]

如果你只想去掉前面的to

result = [re.sub(r'^.*Dream[^ ]* *[^ ]* *(\bto\b)? *', '', a, flags=re.I) for a in text]

【讨论】:

  • 哎呀,我忘了。您是否需要仅在新文本的前面或任何地方删除它? “跑学梦”呢?应该是“跑学”还是“跑学”?
  • 哈哈,不,你说得对,你的建议更适合我,谢谢!
  • 哦,第二个正则表达式的先前版本不适用于“明日之梦”。现在它已经修复了。
猜你喜欢
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2014-09-30
相关资源
最近更新 更多