Python error when comparing strings

I have a problem with this code, it's not comparing the strings and I don't know where else I can look to know the problem:

Please somebody help me, it reads de files, everything is there but it doesn't compare

   # strings.py
def leerArchivo(nombre_archivo):
    archivo=open(nombre_archivo,'r')
    datos = archivo.read()
    datos_separados = datos.split()
    archivo.read()
    archivo.close()
    return datos_separados

def leerArchivo_Lineas(nombre_archivo):
    archivo=open(nombre_archivo,'r')
    lineas = list(archivo)
    return lineas
def estaElementoEn(elemento,lista):
        for token in lista:
                print("Comparando ",type(token)," con: ",type(elemento))
                ## HERE IT'S NEVER COMPARING!!
                if token == elemento:
                        return True
        return False
def esNombre(palabra,lista):
        if palabra[0]=='_':
                for i in range(1,len(palabra)):
                        letra = palabra[i]
                        encontro=False
                        j=0
                        while j<len(lista) and not encontro:
                                if letra == lista[j]:
                                        encontro=True
                                j=j+1
                        if not encontro:
                                return False
                return True
        return False

##1. Leer archivos:
palabrasReservadas = leerArchivo_Lineas('palabrasReservadas.txt')
tiposDatos = leerArchivo_Lineas('tiposDatos.txt')
simbolos = leerArchivo_Lineas('simbolos.txt')
simbolosNombres = leerArchivo_Lineas('simbolosNombres.txt')

##2. Leer  lineas archivo con el codigo
codigo = leerArchivo('codigo.txt')
errores =0;
## Lee cada línea del archivo.
for i in range(0,len(codigo)):
        palabras = codigo[i].split(' ') ## Separa cada elemento de la linea
        for palabra in palabras:
                if  estaElementoEn(palabra,tiposDatos):
                        ##print ("Error en la línea: ",i+1," en el elemento: ",palabra)
                        print("ESTA")

Upvotes: 0

Views: 245

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

The issue is that when you read files and create a list from it as -

def leerArchivo_Lineas(nombre_archivo):
    archivo=open(nombre_archivo,'r')
    lineas = list(archivo)
    return lineas

The newlines at the end are still present in each element of the list. So most probably when you are doing the comparison, you are comparing against the string with newline in it , something like -

'string\n'

You can strip both elements before comparing-

def estaElementoEn(elemento,lista):
        for token in lista:
                print("Comparando ",type(token)," con: ",type(elemento))
                ## HERE IT'S NEVER COMPARING!!
                if token.strip() == elemento.strip():
                        return True
        return False

Upvotes: 2

Related Questions