代码之家  ›  专栏  ›  技术社区  ›  aless80

Python正则表达式:删除以数字结尾的非ASCII字符和单词

  •  1
  • aless80  · 技术社区  · 7 年前

    我试图用“”替换字符串中所有非ASCII字符(重音、符号),然后替换所有以数字结尾的单词。

    #remove all these words:
    re.sub(r'\W|\b[^a-z]*[^a-z]\b',' ', "1 123 - hey2 a2 1a3 ".lower()) 
    >>>' hey2 a2 1a3 '
    #keep all these words:
    re.sub(r'\W|\b[^a-z]*[^a-z]\b',' ', "1st first a2a 2bb esta' ".lower()) 
    >>>'1st first a2a 2bb esta  '          #This works
    

    2 回复  |  直到 7 年前
        1
  •  1
  •   Wiktor Stribiżew    7 年前

    似乎要删除任何非文字字符(与匹配 \W 模式)和任何“文字”(字母/数字序列)/ _ , \w

    因此,您可以使用

    re.sub(r'\W|\b\w*\d\b', ' ', s)
    

    注意,如果在Python 2.x中处理Unicode字符串,则需要传递 re.UNICODE \W \w 支持Unicode。

    图案细节

    • -非文字字符(不是字母、数字或 _
    • |
    • \b -前导词边界
    • \w* * )文字字符
    • \d
    • \b -尾随词边界。

    _ 字符作为非文字字符,替换为 \W [\W_] [^\W_] .

        2
  •  0
  •   lightsong    7 年前

    “*”表示0个或更多个字符。

      re.sub(r'\W|\b[^a-z]*[^a-z]\b',' ', "1 123 - hey2 a2 1a3 ".lower()) 
    
    In [6]: re.sub(r'\W|\b[^a-z].*[^a-z]\b',' ', "1 123 - hey2 a2 1a3 asdasd".lower())
    Out[6]: ' asdasd'