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

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 <

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

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

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

e

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

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: could not convert string to float: 'FOO'

如何将带有符号和文字的行转义,只分析带有数字的行,同时获取具有最小值和最大值的行的指标?

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

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

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() Return True if all characters in the string are alphabetic and there is at least one character, False otherwise

这可能有点矫枉过正,但我​​立即想到的是 RegEx (Regular Expressions),使用 re 库。

这是您将用于浮点数的正则表达式:^[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 <

输出:

Max:  1.0
 line number:  2

Min:  0.000004
 line number:  6

解释:

  1. 编写一个函数来检查字符串是否可以转换为浮点数,这可以通过使用 try 语句和 float()
  2. 来完成
  3. 过滤从文件中读取的行浮动
  4. 找到最小值和最大值
  5. 使用 list.index(<value>)
  6. 在行列表中查找最小值和最大值的索引
  7. 在索引中加 1 以获得行号,因为索引从零开始

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

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 

干杯