Read files in python

1

I need to read a file in python and look for the words that end with ing in it. I had already done my code in C and it worked, now when I pass it to python I run into the problem that I can not read the file. I hope you can help me

    def lecturaArchivo():
estado = 0
caracteres = []
ap = id(caracteres)
archivo = open("Archivo.txt")
salida = open("SalidaIng.txt","w+")

caracteres = archivo.read()

for ap in caracteres:
    if ap == 'i' and estado == 0:
        salida.write("Estado:")
        salida.write(str(estado))
        salida.write("\nLetra:")
        salida.write(str(ap))
        salida.write("\n\n")
        impresion(ap,estado)
        estado = 1
    elif ap == 'n' and estado == 1:
        salida.write("Estado:")
        salida.write(str(estado))
        salida.write("\nLetra:")
        salida.write(str(ap))
        salida.write("\n\n")
        impresion(ap,estado)
        estado = 2
    elif ap == 'g' and estado == 2 and caracteres[i+1] == ' ':
        salida.write("Estado:")
        salida.write(str(estado))
        salida.write("\nLetra:")
        salida.write(str(ap))
        salida.write("\n\n")
        impresion(ap,estado)

    elif ap == 'g' and estado == 2 and caracteres[i+1] !=' ':
        salida.write("Estado:")
        salida.write(str(estado))
        salida.write("\nLetra:")
        salida.write(str(ap))
        salida.write("\n\n")
        impresion(ap,estado)
        estado = 0

    elif ap == ' ':
        salida.write("Estado:")
        salida.write(str(estado))
        salida.write("\nLetra:")
        salida.write(str(ap))
        salida.write("\n\n")
        impresion(ap, estado)
        estado = 0
    else:
            salida.write("Estado:")
            salida.write(str(estado))
            salida.write("\nLetra:")
            salida.write(str(ap))
            salida.write("\n\n")
            impresion(ap,estado)
            estado = 0
ap = id(caracteres[i+1])
    
asked by Alvarez Enrique 24.09.2017 в 04:44
source

1 answer

0

Usually when opening a file it is advisable to use the with , since it is responsible for opening and closing the file automatically. You can also use the slice to know if a word ends with ing . Slice allows you to decide where and from where you want a string using the : sign and allows you to use negative numbers to count from behind. So a simple way to do what you ask is this:

with open('Archivo.txt') as f:
    palabras_con_ing = []
    for line in f:
        words = line.split(" ")
        for word in words:
           if 'ing' == word[-3:]:
              palabras_con_ing.append(word)

print(palabras_con_ing)
    
answered by 24.09.2017 / 18:29
source