How to separate a list with a delimiter?

1

How can I do this exercise?

"Write a program that given a text file, a delimiter, and a list of fields, print only these fields, separated by this delimiter. "

At the moment I have this:

f=open("archivo.txt","r")
delimitador=str("-")
lista=['Hola','Adios','Hoy']
    
asked by Álvaro 09.02.2018 в 19:53
source

1 answer

1

I would do it this way:

f=open("archivo.txt","r")
delimitador=str("-")
lista=['Hola','Adios','Hoy']

linea = f.readline()
aImprimir = ""
primera = True

while linea != "":
    palabras = linea.split(" ")

    for palabra in palabras:
        for clave in lista:
            if clave == palabra:
                if primera:
                    aImprimir+=clave
                    primera = False

                else:
                    aImprimir+=delimitador+clave

    linea = f.readline()

print(aImprimir)

The problem is that this code only works if the file read does not have line breaks, and all the words have to be separated from each other by a space. The latter does not have to be that way, just by changing the line:

palabras = linea.split(" ") #Entre estos parentesis lo que separe las palabras en el archivo
    
answered by 09.02.2018 в 20:54