Python 从文本文件中查找具有最小值和最大值以及行号的行(Get value Error Float Type)

Python 从文本文件中查找具有最小值和最大值以及行号的行(Get value Error Float Type),python,string,type-conversion,row,typeerror,Python,String,Type Conversion,Row,Typeerror,我有一个文件1.txt,在某些行中包含单词和符号,而在其他行中,我只有数字,并且在单词和符号所在的同一行中从来没有数字 FOO > 1.0 BAR < 0.004 FOO FOO < 0.000004 BAR BAR < 我遇到了以下错误 ValueError:无法将字符串转换为浮点:“FOO” 我怎样才能避开有符号和单词的行,只分析有数字的行,同时获得具有最小值和最大值的行的指示符 我可以将所有只包含数字的行提取到一个新文件中(例如使用regex),但我需要知道找到最

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

FOO >
1.0
BAR <
0.004
FOO FOO <
0.000004
BAR BAR <
我遇到了以下错误

ValueError:无法将字符串转换为浮点:“FOO”

我怎样才能避开有符号和单词的行,只分析有数字的行,同时获得具有最小值和最大值的行的指示符

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

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

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
语句,检查
行[0]
是否不是
alpha

如果字符串中的所有字符均为 字母顺序,并且至少有一个字符,否则为False


这可能有些过分,但我马上想到的是使用
re
库的RegEx(正则表达式)

下面是用于浮点的正则表达式:
^[1-9]\d*(\。\d+)?$
。因此,我们可以实现以下代码:

导入csv
进口稀土
行=[]
以open('1.txt',mode='r')作为填充:
reader=csv.reader(填充,分隔符=)
对于读卡器中的行:#每行都是一个列表
if bool(re.match(r'^[1-9]\d*(\.\d+)?$),row:rows.append(row)
minimus=min(行,键=lambda x:float(x[0]))
打印(最小值)
我改变了什么:

我添加了
if bool(re.match…
,结果是
仅在
仅为浮点(或整数)的情况下被追加。

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

代码:

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
输入:

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
说明:

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
  • 编写一个函数来检查字符串是否可以转换为float,这可以通过使用
    try
    语句和
    float()
  • 过滤器从文件中读取的行浮动
  • 查找最小值和最大值
  • 使用
    list.index()
  • 将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 
    

    干杯

    在将当前行添加到行之前,请确认当前行是一个数字。@JohnGordon我不知道如何做,但我会研究一下。
    str.isalpha
    不包括数字吗?你的意思是
    str.isalnum
    ?它的解决方案有一个很大的优势,允许用逗号传递行,否则逗号和单词之间的每个空格都会被忽略将被视为一个新的列。它的解决方案非常有效,甚至能够在单词之间存在逗号的情况下工作,我只是将
    maxindx=index[np.argmax(numbers)]
    改为
    maxindx=index[np.argmax(numbers)]+1
    (同样适用于
    minindx..
    )要更正行索引打印的值,当1.txt在单词之间有一个逗号时。正如Abhi_J解释的那样,我没有指定我希望行标记而不是索引,请原谅我的错误。我在运行解决方案时遇到以下错误:
    File“”,如果bool(re.match(r'^[1-9]\d*(\.\d+?$),row:rows.append(row)^SyntaxError:invalid syntax
    它的解决方案工作得很好,甚至在单词之间有逗号的情况下也能工作,我只将
    lines.Index(my_max))
    改为
    lines.Index(my_max)+1
    当1.txt在单词之间有一个逗号时,要更正行索引打印的值。@yaacovnnnm但是为什么要添加1,索引从零开始,所以输出不是已经正确了吗?@yaacovnnnm你能解释一下你期望的索引是什么吗,我认为这是行号,我认为这是行索引,最简单的方法获取行号将是添加1,因此我将编辑我的答案,而且我认为您应该指定您想要的行号而不是索引。正如您所知,编程中的索引从零开始。@yaacovnnnm没关系,我已经更新了答案,希望它能得到您想要的结果。