从字符串中删除单词,但顺序很重要

时间:2015-10-13 04:57:23

标签: python regex

我有一个要从['as', 'as well as']

等字符串中删除的单词列表

字符串为he is big as hell, as well as an elephant

我想通过列表循环并删除列表中的所有单词

remove=['as','as well as']
sentence='he is big as hell, as well as an elephant'

for i in remove:
    sentence=sentence.replace(" " + i + " "," ")

所需的输出:he is big hell, an elephant

实际输出:he is big hell, well an elephant

基本上删除了as as well as,因此well仍然存在as well as。如果不先将AutoPostBack="false"放在列表中,我该怎么做才能阻止这种情况?

3 个答案:

答案 0 :(得分:6)

根据每个项目的长度进行排序,然后迭代内容,最后进行替换。

>>> sentence='he is big as hell, as well as an elephant'
>>> remove=['as','as well as']
>>> remove = sorted(remove, key=lambda x: len(x), reverse=True)
>>> remove
['as well as', 'as']
>>> for i in remove:
    sentence=sentence.replace(" " + i + " "," ")

>>> sentence
'he is big hell, an elephant'

答案 1 :(得分:2)

我认为最直接的方法是按照长度排序过滤后的单词,以便首先删除需要删除的最长内容。

编辑:这是我发现的按长度排序的方法: remove.sort(key=len, reverse=True)

答案 2 :(得分:0)

Python列表有一个 reverse()方法。如果你知道列表内容的顺序与你想要的顺序相反,那么在删除每个列表项之前实现它。