2014-11-21 43 views
-1

我想知道如何删除以“saison”开头的所有单词。Python - 将所有单词替换为

对于为例:

test = "This is an example of saison1, saison7 and saison58 could be deleted too" 
#test = test.replace("saison1", "") 
#test = test.replace("saison58", "") 

拥有:

test = "This is an example of , and could be deleted too" 

如何做到这一点?

回答

2

您可以使用正则表达式:

import re 

test = re.sub(r'\bsaison\d*\b', '', test) 

这消除其次是0个或多个数字从test文本saison的任何事件。开始和结束时的\b确保您只匹配整个单词,而不是仅发生在包含saison(后跟数字)的中间或末尾的单词,或者以saison开头,但以其他内容结束。

演示:

>>> import re 
>>> test = "This is an example of saison1, saison7 and saison58 could be deleted too" 
>>> re.sub(r'\bsaison\d*\b', '', test) 
'This is an example of , and could be deleted too' 
+0

好的,谢谢。 re是一个我不再控制的模块,语法有点复杂。再次感谢 – Guillaume 2014-11-21 15:43:27

0

另一种解决方案:

>>> ' '.join([ word for word in test.split() if not word.startswith('saison') ]) 
'This is an example of and could be deleted too' 
+0

谢谢,但您的解决方案也删除空间。但是,请你能解答我的问题,因为我不能再提问了。提前致谢! – Guillaume 2014-11-22 08:22:34