【发布时间】:2017-02-05 12:43:09
【问题描述】:
如何使用 RegEx(或 Python 中的其他内容)来满足以下要求? 我需要:
- 删除“梦想”一词(包括其所有词干)
- 删除所有之前的单词(即“dream”这个词后面的所有单词)
- 删除旁边的单词(在它前面/“梦想”的右侧)
- 从所有短语中删除“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