Code is jumping lines - Python

1

Good afternoon!

I would like some help in my project that looks for words (file: Variables.txt) within another (Answers.txt) file and makes the markup Find a word. But by jumping some sentences leaving the final text (Result.txt) blank.

I reduced the size of the bases to facilitate understanding.

Code:

for i in range(1,23):

    arquivo = open('\Variaveis.txt', 'w')

    with open('\Respostas.txt') as stream:

        with open('\Resultado.txt') as arq:

            palavras = arq.readlines()

            for line in stream:

                    for word in palavras:

                        if word.lower() in line.lower():

                            a = (line.strip(), '¬', word + '\n')

                            arquivo.writelines(a)
                            print(a)
                            break

arquivo.close()

Files: -Variables:

oi
mundo
alo
tchau

Answers:

oi mundo
tchau vida solteira
ola meu amigos
mundo grande

Result:

oi mundo¬mundo

tchau vida solteira¬tchau

Expected result:

oi mundo¬oi
tchau vida solteira¬tchau
ola meu amigos¬ola
mundo grande¬mundo

Note: I was running the project writing the variables inside the code and it worked the same as the expected result, but the bases are large and I need to use the variables searching within a txt like this in the above code.

    
asked by anonymous 26.04.2018 / 20:15

1 answer

1

The problem is reading the words:

palavras = arq.readlines()

method readlines returns a line, including \ n at the end. From the documentation:

  

f.readline () reads a single line from the file; a newline character (\ n) is left at the end of the string, and is only omitted on the last line of the file if the file does not end in a newline.

That is, your code only matches when the word is at the end of the search phrase or if it is the last word of your word file.

To resolve this, you should remove \ n from words before fetching them, using the strip method. Something like:

if word.strip().lower() in line.lower():
    a = (line.strip(), '¬', word + '\n')
    arquivo.writelines(a)
    print(a)
    break
    
10.07.2018 / 03:34