删除带空格或“”的单词

2024-09-27 07:19:47 发布

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

这是问题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'或'character'、'noone'},也可能在单词之间带有空格或连字符(-),例如wonderland,no-one,character。你知道吗

代码的问题是,我无法删除space-不匹配的单词。例如wonder landwonderlandwonder-land。你知道吗

我尝试将(-)?|( )?作为正则表达式,但无法使其工作。你知道吗

我需要帮助


Tags: 字符串frominputstringisspace单词about
3条回答

您可以一次使用一个:

对于空间:

对于“-”:

^[ \t]+
@"[^0-9a-zA-Z]+

正则表达式的问题是分组。使用(-)?|( )?作为分隔符并不像您认为的那样。你知道吗

考虑当单词列表为a,b时会发生什么:

>>> regex = "(-)?|( )?".join(["a", "b"])
>>> regex
'a(-)?|( )?b'

您希望这个正则表达式匹配aba ba-b,但显然它没有这样做。它匹配aa-b<space>b!你知道吗

>>> re.match(regex, 'a')
<_sre.SRE_Match object at 0x7f68c9f3b690>
>>> re.match(regex, 'a-')
<_sre.SRE_Match object at 0x7f68c9f3b718>
>>> re.match(regex, 'b')
<_sre.SRE_Match object at 0x7f68c9f3b690>
>>> re.match(regex, ' b')
<_sre.SRE_Match object at 0x7f68c9f3b718>

要解决这个问题,可以将分隔符括在它自己的组中:([- ])?。你知道吗

如果您还想匹配像wonder - land(即在连字符之前/之后有空格的地方)这样的词,您应该使用下面的(\s*-?\s*)?。你知道吗

因为您不知道分隔符在哪里,所以可以生成一个由或regex组成的regex(使用单词边界来避免匹配子单词)。你知道吗

这些正则表达式将在每个字符上使用str.join替换单词的字母和[\s\-]*(将零与“space”或“dash”的多个匹配)

import re

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']

the_regex = "|".join(r"\b{}\b".format('[\s\-]*'.join(x)) for x in phrases_to_remove)

现在来处理“替换除第一个匹配项以外的所有项”部分:让我们定义一个对象,该对象将替换除第一个匹配项以外的所有项(使用内部计数器)

class Replacer:
    def __init__(self):
        self.__counter = 0

    def replace(self,m):
        if self.__counter:
            return ""
        else:
            self.__counter += 1
            return m.group(0)

现在将replace方法传递给re.sub

print(re.sub(the_regex,Replacer().replace,input_string))

结果:

alice is a character from a fairy tale that lived in a . A  about whome  knows much about

(生成的正则表达式非常复杂,顺便说一句:\bw[\s\-]*o[\s\-]*n[\s\-]*d[\s\-]*e[\s\-]*r[\s\-]*l[\s\-]*a[\s\-]*n[\s\-]*d\b|\bc[\s\-]*h[\s\-]*a[\s\-]*r[\s\-]*a[\s\-]*c[\s\-]*t[\s\-]*e[\s\-]*r\b|\bn[\s\-]*o[\s\-]*o[\s\-]*n[\s\-]*e\b

相关问题 更多 >

    热门问题