首页 > 解决方案 > Python - In a text file, strip a line containing a number greater than a certain value

问题描述

I have the following code:

with open(rawfile) as f, open(outfile,'w') as f2:
    for x in f:
      if (':') not in x and ('Station') not in x and('--')not in x and('hPa') not in x:
          f2.write(x.strip()+'\n')

The "...if ___ not in x..." lines identify a line containing that string and removes the line while keeping the rest of the text in the same format. I would like to do this same thing, but remove any line containing a number greater than 10000.

标签: pythonif-statementintegerstrip

解决方案


您应该可以通过合并正则表达式来做到这一点(因为您拥有的是一个字符串)。为此,你可以做类似的事情

import re    

re.findall(r'\d{5,}', str)

这将识别 5 位或更多位的数字。将此包含在某种 if 子句中,以删除您希望消失的数字。

如果您想识别包括 5 位或更多数字在内的整行,您可以使用

re.findall(r'^.+(\d{5,}).+$', str)

推荐阅读