Code is skipping lines - Python

Asked

Viewed 79 times

1

Good afternoon!

I would like a help in my project that seeks words (file: Variables.txt) inside of another file (Answers.txt) and marks if you find a word. But skipping a few sentences leaving blank the final text (Result.txt).

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()

Archives: -Variable:

oi
mundo
alo
tchau

Answers:

oi mundo
tchau vida solteira
ola meu amigos
mundo grande

Upshot:

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 equal to the expected result, however the bases are large and need to use the variables searching inside a txt like this in the code above.

  • has a ' missing by code outside. Have it so only in question or have equal in your code ?

  • sorry, I was taking information from my pc to post here and I also accidentally took the ' .

  • a parallel tip - try to think about your variable names better - you have an "Arq" variable and a "file" variable, both representing different files. Nothing imprede that you call the variables "results, answers, words" - the program would be much easier to read.

1 answer

2

The problem is the reading of words:

palavras = arq.readlines()

the method readlines returns a row, including with the 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 doesn’t 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 in your word file.

To resolve this, you must remove the n of the words before fetching them, using the method strip. Something like:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.