繁体   English   中英

从文本文件中查找具有最小值和最大值的行以及您的行号(获取值错误浮点类型)

[英]Find the line with the min and max value and your line number from text file (Get Value Error Float Type)

我有一个文件 1.txt 在某些行上包含单词和符号,而在其他行上我只有数字,并且在单词和符号所在的同一行上从来没有数字。

FOO >
1.0
BAR <
0.004
FOO FOO <
0.000004
BAR BAR <

我需要的是只分析有数字的行,然后比较找到的数字并打印最大值和最小值。

另外重要的是我知道最小值和最大值的行号(而不是索引)。

我试图通过一些问题来解决这个问题,例如

从文本文件中查找最小值和最大值 - Python e 如何从 *.txt 文件中查找最小值

但是,例如,当我运行代码时

import csv
rows = []
with open('1.txt', mode='r') as infile:
    reader = csv.reader(infile, delimiter=" ")
    for row in reader:  # each row is a list
        rows.append(row)
minimus = min(rows, key=lambda x: float(x[0]))
print(minimus)

我遇到了以下错误

ValueError:无法将字符串转换为浮点数:'FOO'

我怎么能逃脱有符号和单词的行,只分析有数字的行,同时获得具有最小值和最大值的行的指标?

我可以将所有仅包含数字的行提取到一个新文件中(例如使用正则表达式),但我需要知道找到最小值的行的前/后行,然后任何行提取都会增加数字我参与的分析步骤,因为我必须返回分析原始 1.txt 文件。

注意:与该语言的频繁用户相比,我在 Python 方面缺乏经验,但我认为对于 stackoverflow 问题列表来说这很简单,我怀疑这个问题可能已经得到了解答。 但是因为我已经寻找了一些令人满意的问题,但我没有找到它,所以我正在做我自己的问题。

这可能reRegEx (正则表达式)。

这是您将用于浮点数的正则表达式: ^[1-9]\d*(\.\d+)?$ 所以我们可以实现这段代码:

import csv
import re

rows = []
with open('1.txt', mode='r') as infile:
    reader = csv.reader(infile, delimiter=" ")
    for row in reader:  # each row is a list
        if bool(re.match(r'^[1-9]\d*(\.\d+)?$', row): rows.append(row)
minimus = min(rows, key=lambda x: float(x[0]))
print(minimus)

我改变了什么:
我添加了if bool(re.match... ,导致仅rows只是浮点数(或整数)的情况下才附加row

一种可能的方法,不需要任何额外的模块

代码:

def is_float(x):
  try:
    float(x)
    return True
  except:
    return False

with open('url1.txt', 'r') as myfile:
  lines = myfile.readlines()
  
nums = [x for x in lines if is_float(x)]
my_min = min(nums)
my_max = max(nums)

print('Max: ', my_max, 'line number: ', lines.index(my_max)+1)
print()
print('Min: ', my_min, 'line number: ', lines.index(my_min)+1)

输入:

FOO >
1.0
BAR <
0.004
FOO FOO <
0.000004
BAR BAR <

Output:

Max:  1.0
 line number:  2

Min:  0.000004
 line number:  6

解释:

  1. 编写一个 function 来检查字符串是否可以转换为浮点数,这可以通过使用try语句和float()来完成
  2. 从文件读取的行过滤浮动
  3. 找到最小值和最大值
  4. 使用list.index(<value>)列表中查找最小值和最大值的索引
  5. 将 1 添加到索引以获取行号,因为索引从零开始
import csv
rows = []
with open('1.txt', mode='r') as infile:
    reader = csv.reader(infile, delimiter=" ")
    for row in reader:
        if not row[0].isalpha():
            rows.append(row[0])
    print(rows)
minimus = min(rows, key=lambda x: float(x[0]))
print(minimus)

合并if语句来检查row[0]是否不是alpha

str.isalpha()如果字符串中的所有字符都是字母并且至少有一个字符,则返回 True,否则返回 False

我建议一个简单的解决方案,通过使用 try except 语句收集所有数字及其索引。 在两个列表中收集数字和索引后,您可以通过例如使用 numpy package 来找到最小值和最大值。

import numpy as np

numbers, indices = [],[]
with open("1.txt") as my_text_file:
    for i, line in enumerate( my_text_file.readlines() ):
        try:
            numbers.append( float(line) )
            indices.append( i )
        except:
            pass

maxvalue = np.max( numbers )
minvalue = np.min( numbers )
maxindx  = indices[ np.argmax( numbers ) ]
minindx  = indices[ np.argmin( numbers ) ]

print("The maximum value is found at line "+str(maxindx)+" with the value "+str(maxvalue))
print("The minimum value is found at line "+str(minindx)+" with the value "+str(minvalue))

对于提供的 1.txt 文件,这将产生打印输出

The maximum value is found at line 1 with the value 1.0                                                                 
The minimum value is found at line 5 with the value 4e-06 

干杯

暂无
暂无

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

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