【问题标题】:Python: Regex code not able to remove ' and - from textPython:正则表达式代码无法从文本中删除 ' 和 -
【发布时间】:2021-02-22 20:29:17
【问题描述】:

我有一大段文本,下面是其中的一个示例。

'tis too true! How smart a lash that 
speech doth give my conscience! The harlot's cheek beautied with plastering art Is not more ugly to the thing

我想去掉所有不是“.?!”的标点符号。我想我是用下面的代码这样做的:

hamsplits2 = re.sub(r'[^[a-z.?!\s]]', "", hamsplits1) # substitute any character that is not what's in box

但代码似乎不起作用,因为当我 print(hamsplits2) 时,我仍然得到撇号和破折号。

how smart a lash that 
speech doth give my conscience! the harlot's cheek beautied with plastering art is not more ugly to the

我的正则表达式有什么问题导致它无法删除撇号和破折号?

【问题讨论】:

    标签: python regex punctuation


    【解决方案1】:

    您的 [^[a-z.?!\s]] 正则表达式是“格式错误”的模式。它包含两部分,[^[a-z.?!\s]] 原子。 [^[a-z.?!\s] 是一个否定字符类,它匹配除 [、小写字母、.?! 和空格之外的任何字符,] 匹配文字 ]。因此,它匹配两个字符的组合,如]]1] 等。

    你可以使用

    hamsplits2 = re.sub(r'[^\w\s.?!]|_', '', hamsplits1)
    

    regex demo

    [^\w\s.?!]|_ 正则表达式匹配除.?!_ 以外的标点字符,或者匹配_(这是因为\w 匹配下划线,而不仅仅是字母和数字)。

    更多详情

    • [^\w\s.?!] - 一个否定字符类,匹配除单词字符 (\w)、空白字符 (\s)、.?! 以外的任何字符
    • | - 或
    • _ - 一个下划线。

    【讨论】:

    • 感谢您的详细解释。你能详细说明为什么我最初的尝试没有奏效吗?
    • @PineNuts0 我在第一段添加了解释。
    • 我明白了......但为什么我原来的正则表达式不匹配 - 和 ' ?
    • @PineNuts0 它匹配两个-char组合。见your regex demo
    【解决方案2】:

    您需要转义第一个 ],以便将其视为文字字符,而不是终止第一个 [

    hamsplits2 = re.sub(r'[^[a-z.?!\s\]]', "", hamsplits1)
    

    如果您不是要在应保留的标点符号集中包含 [],请将它们都从字符集中删除:

    hamsplits2 = re.sub(r'[^a-z.?!\s]', "", hamsplits1)
    

    【讨论】:

      【解决方案3】:

      你可以试试这个正则表达式:[^\w\d\.\?\!\s],意思不是单词、数字,也不是.?!,也不是空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        相关资源
        最近更新 更多