Restart in cycle for

1

I am doing a program which reads a file (which contains in lines words, is attached) and has to return a new file with the word in question and the sum of its characters (these I generated from a dictionary ). The problem is that it does everything but accumulates the sums, that is, from the value of the previous word, adds the new value instead of zero. Could someone help me solve this problem?

IMAGE OF THE TEXT FILE:

CODE:

def glich(pal):
    global c
    valores={}
    for i in range (27):
        abc = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        valores[abc[i]] = i


    palabra = pal.upper()
    #c = 0
    for letra in palabra:
        a = valores[letra]
        c = c+a
    return c


c=0


arch=open("palabras.txt","r")

val=[]
palas=[]
for linea in arch:
    glich(linea.rstrip("\n"))
    palas.append(linea.rstrip("\n"))
    val.append(c)
arch.close()


nuevo=open("suma.txt","w")

for i in range(len(palas)):
    nuevo.write(palas[i]+","+str(val[i])+"\n")

HOW TO LEAVE:

HOW IT COMES OUT:

    
asked by Frank 19.11.2018 в 20:51
source

1 answer

1

You can do it this way:

# imports 
# pprint es para una impresion de arreglos mas legible y string para el alfabeto
from pprint import pprint
import string

#con libreria string
#str = string.ascii_lowercase

#sin libreria string
str = "abcdefghijklmnopqrstuvwxyz"
# abrimos el documento
with open("palabras.txt","r") as f:
    # hacemos un loop de las palabras en el archivo y luego otro loop de las letras en la palabra con el
    # index() no das la posicion de la letra en el string de letras minusculas a eso le sumamos 1 y lo vamos sumando 
    val = [ ( x.rstrip('\r\n' ),sum( (str.index(i)+1) for i in x if i.rstrip('\r\n') )  ) for x in f.readlines() if x.strip() ]
pprint(val) 

result:

[('flojo', 58), ('excelente', 93), ('conocimiento', 135), ('trabajo', 67)]
    
answered by 19.11.2018 / 21:44
source