简体   繁体   English

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

[英]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.

相关问题 在文本文件中查找大于一定数量的数字 - Find amount of numbers in a text file that are greater than a certain number 在 Python Selenium 中等待某个值大于等于某个数 - Waiting for a value to be greater than or equal to a certain number in Python Selenium 如何从文本文件的每一行中删除一段文本? - How to strip a certain piece of text from each line of a text file? 如果差值大于某个值,则在列表中保留连续数字 - Keep consecutive number in list if the difference greater than a certain value 计算 numy.ndarray 中大于某个值的元素数 - Counting number of elements greater than a certain value in a numy.ndarray 计算字典中大于Python中某个数字的值? - Counting values in a dictionary that are greater than a certain number in Python? 如何在Python的已保存文件中的包含某些文本的行之后打印行? - How do I print a line following a line containing certain text in a saved file in Python? 选择大于某个值的Python字典元素 - Selecting elements of a Python dictionary greater than a certain value 如何检查 integer 是否大于 python 中的某个值? - How to check if an integer is greater than another by a certain value in python? 列表中大于某个数字的值的数量 - number of values in a list greater than a certain number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM