替换字符串的Python正则表达式

2024-06-06 20:26:52 发布

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

如何使用RegEx(或者Python中的其他东西)满足以下需求? 我需要:

  1. 去掉“梦”这个词(包括它的所有词干)
  2. 删除前面的所有单词(即“梦想”后面的所有单词)
  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']

Tags: oftoinliveworld单词cartomorrow
1条回答
网友
1楼 · 发布于 2024-06-06 20:26:52

这将提供所需的输出

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]

相关问题 更多 >