【问题标题】:Removing all text within double quotes删除双引号内的所有文本
【发布时间】:2023-01-11 00:21:50
【问题描述】:

我正在对 Python 中的一些文本进行预处理,并希望摆脱文本中出现在双引号中的所有文本。我不确定该怎么做,非常感谢您的帮助。下面是一个可重现性最低的示例,供您参考。先感谢您。

x='The frog said "All this needs to get removed" something'

所以,我想得到的几乎是 'The frog said something',方法是从上面的 x 中删除双引号中的文本,我不知道该怎么做。再次感谢。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    使用正则表达式替换:

    import re
    
    x='The frog said "All this needs to get removed" something'
    res = re.sub(r's*"[^"]+"s*', ' ', x)
    print(res)
    

    The frog said something
    

    • s* - 匹配可选的空白字符
    • " - 按原样匹配" char
    • [^"]+ - 匹配除"之外的任何字符(通过^符号确保)一个或多个

    【讨论】:

    • 这将添加如果引号周围没有s,则留一个空格,但我想这很好。
    • @RomanPerekhrest,非常感谢您的快速回复。这将有助于我的理解,如果你能将代码第二行中的正则表达式(只是 re.sub 函数中的第一个参数)分解为步骤......这样我可以更容易地学习如何去做下次我自己。再次感谢!
    • @Dave,好的,看我的解释
    • @RomanPerekhrest,谢谢你很有帮助。最后一个问题—— s 是否确保双引号内的文本在删除之前允许有前导或尾随空格?
    • @RomanPerekhrest,谢谢,这非常有帮助。
    【解决方案2】:

    如果你想使用索引和切片:

    s='The frog said "All this needs to get removed" something'
    
    # To get the index of both the quotes
    [i for i, x in enumerate(s) if x == '"']
    #[14, 44]
    
    s[:13]+s[45:]
    #'The frog said something'
    

    【讨论】:

      【解决方案3】:

      快速修复假设 " 在字符串中是平衡的,即是偶数,并且双空格不相关。

      x = 'The frog said "All this needs to get removed" something'
      
      x_new = ''.join(x.split('"')[::2]).replace('  ', ' ')
      

      最终,可以使用str.count检查这些条件:

      if x.count('"') % 2 != 0:
         raise Exception('Double quotes are not balanced')
      
      if x.count("  ") > 0:
         raise Exception('Double spaces are present')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        • 2014-05-25
        • 2014-05-29
        • 1970-01-01
        • 2014-12-25
        • 2020-01-19
        相关资源
        最近更新 更多