繁体   English   中英

Python-在文本文件中,删除包含大于某个值的数字的行

[英]Python - In a text file, strip a line containing a number greater than a certain value

我有以下代码:

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')

“ ... if ___ not in x ...”行标识包含该字符串的行,并删除该行,同时其余文本保持相同格式。 我想做同样的事情,但是删除任何包含大于10000的行。

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

import re    

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

这将标识具有5个或更多数字的数字。 在某种if子句中包含此内容可删除您希望删除的数字。

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

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

最简单的是使用regexp和分组:

match = re.match(r'regexpToIdentyMyNumber(\d+)', x)
my_number = float(match.group(1)))
if my_number > 10000:
    continue # do my thing

基本上,您需要定义一个标识您的数字的模式,然后使用括号将数字( \\d+ )声明并保存为一个组,然后可以将其用于进行进一步的计算。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM