[英]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. “ ... if ___ not in x ...”行标识包含该字符串的行,并删除该行,同时其余文本保持相同格式。 I would like to do this same thing, but remove any line containing a number greater than 10000. 我想做同样的事情,但是删除任何包含大于10000的行。
You should be able to this by incorporating Regex (since what you have is a string). 您应该可以通过合并Regex来做到这一点(因为您拥有的是字符串)。 For that, you could do something like 为此,您可以做类似的事情
import re
re.findall(r'\d{5,}', str)
This will identify numbers with 5 or more digits. 这将标识具有5个或更多数字的数字。 Include this in some sort of if clause to remove the numbers you desire gone. 在某种if子句中包含此内容可删除您希望删除的数字。
If you're wanting to identify the whole line including a 5 digit or more number, you can use 如果您想识别包括5位或更多数字的整行,可以使用
re.findall(r'^.+(\d{5,}).+$', str)
The easiest is to use regexp and grouping: 最简单的是使用regexp和分组:
match = re.match(r'regexpToIdentyMyNumber(\d+)', x)
my_number = float(match.group(1)))
if my_number > 10000:
continue # do my thing
Basically you need to define a pattern that identifies your number and then use the parentheses to declare and save the number (the \\d+
) as a group, which can then be used to do further calculations. 基本上,您需要定义一个标识您的数字的模式,然后使用括号将数字( \\d+
)声明并保存为一个组,然后可以将其用于进行进一步的计算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.