【问题标题】:Removing lines with only digits - regex删除只有数字的行 - 正则表达式
【发布时间】:2018-06-10 09:28:54
【问题描述】:

我对 python 和正则表达式都很陌生。我正在尝试处理一个文本文件,我想在其中删除只有数字和空格的行。这是我正在使用的正则表达式。

^\s*[0-9]*\s*$

我能够匹配我想要删除的行(在 notepad++ 查找对话框中)。

但是当我尝试对 python 做同样的事情时,这些行不匹配。是正则表达式本身有问题还是我的 python 代码有问题?

我正在使用的 Python 代码:

contacts = re.sub(r'^\s*[0-9]*\s*$','\n',contents)

示例文本

Age:30
Gender:Male



20 


Name:संगीता शर्मा
HusbandsName:नरेश कुमार शर्मा
HouseNo:10/183
30 30
Gender:Female


21 

Name:मोनू शर्मा
FathersName:कैलाश शर्मा
HouseNo:10/183
30
Gender:Male

【问题讨论】:

    标签: regex python-2.7


    【解决方案1】:

    在多行模式下使用re.sub

    contacts = re.sub(r'^\s*([0-9]+\s*)+$','\n',x, flags=re.M)
    

    Demo

    如果您希望开始 ^ 和结束 $ 锚点启动,那么您希望处于多行模式。

    此外,使用以下表示仅包含数字簇的行,可能用空格分隔:

    ^\s*([0-9]+\s*)+$
    

    【讨论】:

      【解决方案2】:

      你甚至不需要正则表达式,一个简单的str.translate() 来删除你不感兴趣的字符并检查是否有剩余的东西就足够了:

      import string
      
      clear_chars = string.digits + string.whitespace  # a map of characters we'd like to check for
      
      # open input.txt for reading, out.txt for writing
      with open("input.txt", "rb") as f_in, open("output.txt", "wb") as f_out:
          for line in f_in:  # iterate over the input file line by line
              if line.translate(None, clear_chars):  # remove the chars, check if anything is left
                  f_out.write(line)  # write the line to the output file
              # uncomment the following if you want added newlines when pattern matched
              # else:
              #     f_out.write("\n")  # write a new line on match
      

      这将为您的示例输入生成:

      年龄:30
      性别:男
      名称:संगीता शर्मा
      丈夫姓名:नरेश कुमार शर्मा
      房屋编号:10/183
      性别女
      名称:मोनूशर्मा
      父亲姓名:कैलाश शर्मा
      房屋编号:10/183
      性别:男

      如果您想将匹配的行替换为新行,只需取消注释 else 子句即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多