【发布时间】:2019-01-20 00:33:18
【问题描述】:
这是问题here的扩展
现在就像在链接的问题中一样,答案使用space? 作为正则表达式模式来匹配带有空格或没有空格的字符串。
问题陈述:
我有一个字符串和一组短语。
input_string = 'alice is a character from a fairy tale that lived in a wonder land. A character about whome no-one knows much about'
phrases_to_remove = ['wonderland', 'character', 'noone']
现在我要做的是从input_string 中删除数组phrases_to_remove 中最后出现的单词。
output_string = 'alice is a character from a fairy tale that lived in a. A about whome knows much about'
注意:要删除的词可能会出现在字符串中,也可能不会出现,如果出现,它们可能以相同的形式出现 {'wonderland' or 'character', 'noone'}或者它们可能在单词之间出现空格或连字符 (-),例如神奇的土地,没有人,性格。
代码的问题是,我无法删除 space 或 - 不匹配的单词。例如 wonder land 和 wonderland 和 wonder-land。
我尝试将(-)?|( )? 用作正则表达式,但无法正常工作。
我需要帮助
【问题讨论】:
-
您是否在替换列表中尝试过
r'\bwonder[ \-]?land\b'? -
@Jean-FrançoisFabre 这是一个正则表达式吗?
-
这是一个正则表达式。
re.sub(r'\bwonder[ \-]?land\b',"",input_string)删除单词 all-right(保留单词边界作为奖励) -
@Jean-FrançoisFabre 这个词 Wonderland 不是硬编码的。要求是删除所有匹配的单词,无论字母之间的
-或space是什么 -
在这种情况下,您可以在每个字母之间插入空格/破折号,因为您不知道单词何时“中断”