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

用一个词替换各种格式的数字

  •  0
  • N08  · 技术社区  · 7 年前

    我有一个很长的句子,我想用一个特定的词代替所有的数字。数字有不同的格式,例如,

    36
    010616
    010516 - 300417
    01-04
    2011 12
    

    python中是否有函数用一个词(比如“integer”)替换这些类型的事件,或者regex如何查找这些事件?

    例子:

    "This is a 10 sentence with date 010616 and intervals 06-08 200-209 01 - 09 in years 2012 26"
    

    应该变成

    "This is a NUMBER sentence with date NUMBER and intervals NUMBER NUMBER NUMBER in years NUMBER NUMBER"
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Rakesh    7 年前

    使用正则表达式。

    import re
    s = "This is a 10 sentence with date 010616 and intervals 06-08 200-209 01 - 09 in years 2012 26"
    print( re.sub("\d+", "NUMBER", s) )
    

    输出:

    This is a NUMBER sentence with date NUMBER and intervals NUMBER-NUMBER NUMBER-NUMBER NUMBER - NUMBER in years NUMBER NUMBER
    
        2
  •  1
  •   SpghttCd    7 年前
    re.sub('((?<=^)|(?<= ))[0-9- ]+(?=$| )', 'NUMBER', s)
    'This is a NUMBER sentence with date NUMBER and intervals NUMBER in years NUMBER'
    

    它的作用是:

    寻找带负号和空格的数字 [0-9- ]+

    在匹配之前以空格或字符串开头 ((?<=^)|(?<= ))

    以及匹配后字符串的空格或结尾 (?=$| )