简体   繁体   English

比较Python中.txt文件中的连续数字

[英]Comparing consecutive Numbers in .txt file in Python

I am using Python 2.7 and I am struggling with a problem in my script: 我正在使用Python 2.7,并且在脚本中遇到问题:

I want to read a .txt file and compare numbers in consecutive rows, and find at least 5 consecutive ones, which are below a threshold and save their position (the numbers of the lines) into another .txt file and stop when the input file is completed. 我想读取一个.txt文件并比较连续行中的数字,并找到至少5个连续的,低于阈值的行并将其位置(行数)保存到另一个.txt文件中,并在输入文件时停止完成了。

Could anyone think of a code to implement this? 谁能想到实现此目的的代码? I've tried with fobj and numbers but it won't work. 我已经尝试过使用fobj和数字,但是它不起作用。

My input file looks something like this: 我的输入文件如下所示:

0.1123
0.1233
0.5343
3.7654
-3.4325
-2.9832
10.3289
11.3890
...

And my desired output would be the lines (in this case lines 0 to 5 if we assume the threshold to be 10.0): 我想要的输出将是行(在这种情况下,如果我们将阈值假定为10.0,则行0到5):

0
1
2
3
4
5
...

Thanks in advance! 提前致谢!

If I understand correctly this should be what you are looking for. 如果我理解正确,那么这应该是您想要的。 You would need to tweak the code a bit if you only wanted a certain number of entries. 如果您只想要一定数量的条目,则需要稍微调整一下代码。

threshold = 10
old_file = 'old_file.txt'
with open(old_file, 'r') as document:
    values = [x for x, value in enumerate(document) if float(value) < threshold]

new_file = open('new_file.txt', 'w')
for x in values:
    new_file.write(str(x) + '\n')

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

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