【问题标题】:re.sub not converting apostrophes to spaces [closed]re.sub 不将撇号转换为空格 [关闭]
【发布时间】:2020-07-08 02:20:23
【问题描述】:

说明

我正在尝试让re.sub() 将所有撇号和逗号替换为空格。

代码

content = "he knew that the people were right. I'm I'm I'm I'm I'm"
content = re.sub("^[^*$<,>?!']*$", ' ', content)

OUTPUT:
"he knew that the people were right. I'm I'm I'm I'm I'm"

这会返回相同的字符串,并且不会将任何内容转换为空格。

我不确定我做错了什么。

【问题讨论】:

    标签: python python-3.x regex


    【解决方案1】:

    我不确定你是如何得到你的替换代码的,但恐怕它太离谱了。正如所写,它说“只有当字符串不包含星号、美元符号、小于号、逗号、大于号、问号、感叹号或撇号时,才用一个空格替换整个内容。”

    如果你想用空格替换撇号和逗号,正则表达式会更简单一些:

    >>> content = "he knew that the people were right. I'm I'm I'm I'm I'm"
    >>> re.sub(r"[,']", ' ', content)
    'he knew that the people were right. I m I m I m I m I m'
    

    正则表达式就是这样:

    [,']  matches either a comma or an apostrophe 
    

    一般来说,正则表达式构造[...],称为字符类,匹配括号中包含的任何单个字符。有一些例外情况,其中一个在您的原始代码中使用:如果 [ 之后的第一个字符是插入符号 (^),则否定字符类,因此它匹配任何单个字符括号中剩下的一个。

    所以你原来的正则表达式分解如下:

    ^ match only at the start of the string
    [^...] match anything EXCEPT these characters
    * 0 or more times
    $ match only at the end of the string
    

    结果是正则表达式与整个字符串匹配(因为 ^ 和 $),并且只有当该字符串在插入符号后的括号内不包含这些字符时,匹配才会成功。如果它成功了,因为它匹配整个字符串,整个字符串被替换 - 这意味着即使你原来的 re.sub 匹配字符串,它只会返回一个空格,不管输入字符串是什么。

    【讨论】:

      【解决方案2】:
      1. 如果你只想替换单个字符,不要匹配整个字符串。 ^ 匹配字符串开头 .* 匹配字符串结尾
      2. 总是转义特殊字符 然后您的解决方案变为(插入逗号以显示它也被替换)
      content = "he knew that(,) the people were right. I'm I'm I'm I'm I'm"
      re.sub("[\',\,]", ' ', content)
      

      【讨论】:

        【解决方案3】:

        我建议使用.replace() 函数,如下所示:

        content = "he knew that the people were right. I'm I'm I'm I'm I'm"
        content = content.replace("'", " ")
        
        print(content)
        

        现在的输出是:

        he knew that the people were right. I m I m I m I m I m
        

        希望这会有所帮助!

        【讨论】:

          猜你喜欢
          • 2015-01-13
          • 1970-01-01
          • 2015-05-15
          • 1970-01-01
          • 2011-10-11
          • 1970-01-01
          • 2014-08-19
          • 1970-01-01
          • 2012-02-05
          相关资源
          最近更新 更多