代码之家  ›  专栏  ›  技术社区  ›  iam.Carrot

删除其中带有空格或“-”的单词Python

  •  1
  • iam.Carrot  · 技术社区  · 6 年前

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

    phrases_to_remove input_string .

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

    注意:

    代码的问题是,我无法删除包含 space - 不匹配。例如 wonder land wonderland wonder-land .

    我试过了 (-)?|( )?

    我需要帮助

    3 回复  |  直到 6 年前
        1
  •  1
  •   Giacomo Alzetta    6 年前

    正则表达式的问题是分组。使用 (-)?|( )? 作为一个分隔符并不像你想象的那样。

    a,b :

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

    你想让这个正则表达式匹配 ab a b a-b ,但显然不是这样。它匹配 a , a- 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*)? .

        2
  •  1
  •   Jean-François Fabre    6 年前

    这些正则表达式将交替使用单词的字母和 [\s\-]* str.join 在每个字符上

    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
    

    (生成的regex相当复杂,顺便说一句: \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 )

        3
  •  0
  •   jvjayavardhan    6 年前

    您可以一次使用一个:

    对于空间:

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