Find the highest value of any python file

Asked

Viewed 1,417 times

0

Good night Devs!

I am having certain difficulties in manipulating python files.
I have a TXT file with float numbers.

Example:

numbers.txt

10 130 20
77 23
9 10 20.26 -20.26 2

Having this data in hand, I have to go down line by line, check whether the file is empty or not, if it’s empty I have to find the highest value inside the archive and their average, and this is where my doubt gains strength, How can I recover this data to perform the calculations? i tried to save to a vet, but the data becomes strings and do not accept the conversion to Float.

I’ll be dropping my code:

#Ler o nome do arquivo
#Abrir o arquivo caso exista
#Verificar o Maior valor possivel
#Verificar a Média dos valores
#Imprimir média e Valores


def pulaLinha ():
    print('\n')



arq  = open("numeros.txt", "r") #ABRE O ARQUIVO TXT

########################################
#CALCULAR O TOTAL DE LINHAS DO ARQUIVO|#
########################################

text = arq.readlines()# GUARDA TODOS OS DADOS DO ARQUIVO
tot  = 0 #TOTAL DE LINHAS
for i in text: #CALCULA O TOTAL DE LINHA DO ARQUIVO
    tot = tot+1 #SALVA O TOTAL EM UM ACUMULADOR

########################################
#VERIFICAR SE O ARQUIVO É VAZIO OU NÃO #
########################################

if (tot == 0):#SE TOT DE LINHAS FOR IGUAL A 0
    print("ARQUIVO VAZIO! ") #IMPRIME O ERRO
    arq.close() # FECHA ARQUIVO
    exit()

#SE O TOT DE LINHAS FOR MAIOR QUE 0
for linha in text:#ARMAZENA OS VALORES EM LINHA
    print(linha, end=" ") #IMPRIME OS VALORES DE LINHA // IMPRIME O ARQUIVO


vet = []
for j in text:
    vet.append(j)
    
    



arq.close()#FECHA O ARQUIVO TXT

If anyone can help me I’d be grateful.

Thank you for your attention.

  • Is it a number per line? You have one line 9 10 20.26 -20.26 2 what’s supposed to be that?

  • @Miguel- There is a file, this file has lines, I want to find the highest value inside the file, it can be anywhere, and also find the average values.

  • According to your text, it’s only one number per line, but the contents of the file you posted say otherwise. That’s what Miguel asked: will it be just one number per line or can there be more than one on the same line?

2 answers

2

Ok, I’ll put the steps for you to get the desired results, I didn’t worry about details such as if the file exists or if this empty, this is with you (This link can adjure), follows the main logic:

from scipy import mean

# Load File
lf = list(open('numeros.txt','r'))

# Remove /n
lf = [s.rstrip() for s in lf]

# Convert into a list of list
lfl = [_str.split(' ') for _str in lf]

# flaten
fflaten = [float(n) for sub_list in lfl for n in sub_list]

print ('Média: ', mean(fflaten) )
print ('Vl Máximo: ', max(fflaten))
print ('Vl Minimo: ', min(fflaten))

Média:  28.1
Vl Máximo:  130.0
Vl Minimo:  -20.26

See a notebook of this code working on this link.

In time: To treat exceptions of the type if the file exists or not, see the examples in this answer.

  • In this case I am obliged to use scipy?

  • Scipy was only to use the function Mean, if you do not need it can dispense, or can do its own function to calcar the media.

  • Ah yes, thank you very much :D

  • +1 by list(open()). I’ve never seen this use. Always use open(). readlines()

0

First, let’s consider that the file can have any type of content (both numbers and text), without a defined format. That is, there can be multiple lines and multiple values in each line, and the number can vary in the same number. For example, the file numeros.txt given in the question:

numbers.txt

10 130 20
77 23
9 10 20.26 -20.26 2

The code must correctly identify the following values: 10, 130, 20, 77, 23, 9, 10, 20.26, -20,26, 2.

To do so, we do:

import re

# busca os valores reais no arquivo numeros.txt:
numeros = [float(i) for i in re.findall(r"-?\d+\.?\d*", open("numeros.txt").read())]

# Exibe a lista de números:
print(numeros)

The exit will be:

[10.0, 130.0, 20.0, 77.0, 23.0, 9.0, 10.0, 20.26, -20.26, 2.0]

The highest value is found by the function max:

>>> print("Maior valor:", max(numeros))
Maior valor: 130.0

And the average is calculated by dividing the sum of the numbers by the quantity:

>>> print("Média:", sum(numeros)/len(numeros))
Média: 28.1

The complete code then stays:

import re

numeros = [float(i) for i in re.findall(r"-?\d+\.?\d*", open("numeros.txt").read())]

if numeros:
    print("Maior valor:", max(numeros))
    print("Média:", sum(numeros)/len(numeros))
else:
    print("Nenhum número encontrado")

The equivalent code, only more readable for humans:

import re

# Expressão regular de números reais:
pattern = re.compile(r"-?\d+\.?\d*")

# Busca todos os números do arquivo:
with open("numeros.txt") as f:
    numeros = pattern.findall(f.read())
    
# Converte os números para float:
numeros = [float(i) for i in numeros]

if numeros:
    print("Maior valor:", max(numeros))
    print("Média:", sum(numeros)/len(numeros))
else:
    print("Nenhum número encontrado")

The working code can be seen here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.