E
As I said in my comment you will have to keep the values separately but in a tupla, this way ('file1.txt',40)Simulate your function to determine the value.import random
files = [] #aqui guardaremos los valores
for i in range(10):
#esto simplemente genera los nombres y valores
myFile = f'file{i}.txt'
porcent = random.randint(0,100)
#añadimos a la lista pero como TUPLAS
files.append((porcent,myFile))
#aqui ordenamos los valores segun su % que es el primer valor
files = sorted(files, reverse=True)
#imprimimos
print(files)
Departure[
('file8.txt', 89),
('file6.txt', 60),
('file3.txt', 45),
('file2.txt', 37),
('file1.txt', 29),
('file7.txt', 23),
('file0.txt', 17),
('file9.txt', 17),
('file4.txt', 13),
('file5.txt', 9)
]
If we want to see the values in a pretty way, we only go through them with a forfor p,f in files:
print(f'{f}: {p}%')
Departurefile8.txt: 89%
file6.txt: 60%
file3.txt: 45%
file2.txt: 37%
file1.txt: 29%
file7.txt: 23%
file0.txt: 17%
file9.txt: 17%
file4.txt: 13%
file5.txt: 9%
Thanks to @abulafia's comment remove the lambda function, it doesn't have much effect, but still read everything to understand it Implemented the codeYour code has errors, the else will run if a different exception is generated than you specified. this is arranged by moving the content of the else Al try.Your function contar_palabras instead of adding the percentage we return a tupla (porcentaje, fileName) this since the function only receives a file, if you received a list, the ordered list would be returned.archivo = ''
#buscar = input("Ingrese lo que desea buscar: ")
buscar = 'de talle al suyo'
words = buscar.split(" ") #Separo la cadena de texto en palabras.
total = len(words) # Cuento la cantidad total de palabras en mi lista.
num_file = [1,2]
def contar_palabras (archivo):
#ponemos todo en el try
try:
with open(archivo, "r") as arch_obj:
lineas = arch_obj.read()
cant = 0
for i in words: #Para cada palabra de la lista:
if " " + i + " " in lineas or " " + i + "." in lineas or "" + i + " " in lineas or " " + i + "" in lineas or " " + i + "" in lineas : #Si la palabra existe en el archivo.
cant = cant+1 #Suma 1 a la variable cant que indica la cantidad de palabras que existen en el file.
perc = 100 * cant / total
else: #Si no existe la palabra, no suma nada y solo calcula el porcentaje.
perc = 100 * cant / total
#la función solo lee un archivo a la vez por lo que no servira de nada ordenar la lista aqui.
result = (perc,archivo) #creamos la tupla
# result = sorted(result, reverse=True)
print(archivo + ": " + str(perc) +'%') #luego mostramos
return result #retornamos el resultado
except FileNotFoundError:
mensaje = "El archivo " + archivo + " no existe."
print(mensaje)
num = 0
archivos = [] #Se crea una lista vacia
resultados = [] #aqui se almacenaran los resultados
archivos.pop(0)
for i in num_file:
num = num+1
archivos.append('file{}'.format(num) +'.txt') #Agrego un file a inspeccionar
for i in archivos:
res = contar_palabras(i) #esto nos retorna una tupla (%,file)
resultados.append(res) #lo añadimos a la lista de resultados antes creada
#una vez finalice el bucle recién se ordena la lista de resultados
resultados = sorted(resultados, reverse=True)
print(resultados)
This would be all, you can optimize your cycles for with a list compression, but that's another theme.