Assign text in TXT file to a variable

Asked

Viewed 619 times

1

Good morning!

I am running a project that is working normally, but I would like to automate it more to gain time in operation. In case my project takes in a text file the main words I described within the variable "word" and put it to me at the end of each sentence of the text file if you find any words.

However the variables of word I am writing inside the code and I would like to turn it into a file of . txt as well and so I can make a loop within the project because there are 21 different projects.

Project that is running normally:

    arquivo2 = open(r'\Texto para a\Vers2.txt', 'w')

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


    for line in stream:
        for word in ['(3)produto', 
'/PRODUTOS', 
'ATENDIMENTOPRODUTOS', 
'PRODUTO', 
'produto!', 
'Produto,', 
'produto.', 
'produto?', 
'PRODUTOR', 
'PRODUTOS', 
'produtos!', 
'produtos!!', 
'produtos,', 
'produtos.', 
'produtos...', 
'PRODUTOS/SERVIOS', 
'produtos;', 
'PRODUTOSDEVERIA', 
'PRODUTOSPIC', 
'PRODUTOSQUE', 
'COBRAR', 
'autro']:
            if word.lower() in line.lower():

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

              arquivo2.writelines(a)                         

              break

arquivo2.close()

This part from the [] that would like to turn into archive. I have tried some solutions I saw here on the site but none worked. They can help me?

1 answer

1


create a file called.txt words containing the words:

(3)produto 
/PRODUTOS 
ATENDIMENTOPRODUTOS 
PRODUTO 
produto! 
Produto 
produto. 

Read it and save the values in a list

with open('palavras.txt','r') as arq:
     palavras = arq.readlines()

ready now make the loop for on the list words to compare with the text you are looking for

for line in stream:
    for word in palavras:

Don’t forget to treat for line breaks \n of your.txt word file at the time of comparing the values

  • Perfect Willian! worked very well, thank you very much!

Browser other questions tagged

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