How to correlate files from two txt files in Python

2

I would like to know a way to correlate equal words to different txt files. It will read the words from a txt file and look up those words in the other txt file.

    
asked by anonymous 07.10.2017 / 17:02

2 answers

2

To see the elements in common between two files (word lists) intersect your sets:

with open('arquivo1.txt') as f1, open('arquivo2.txt') as f2:
    content1 = f1.read().split() # dividir por palavras
    content2 = f2.read().split() # dividir por palavras
comuns = set(content1) & set(content2) # {paravras, comuns, nos, dois, arquivos}

Sets in python

DEMONSTRATION

    
07.10.2017 / 17:31
0

Well ... I would do it this way:

First you would save the contents of each file to a list, using lista = file.read() , then would make a newlista = lista.split() what would take each word and put it in a position in the list, which would result in something like this:

conjunto_A = ['oi','tchaum','ontem','amanha']
conjunto_B = ['oi','tchaum','ontem','amanha','tarde','noite']

palavras_C = [item for item in conjunto_A if item  in conjunto_B]
print(palavras_C)

Having the word lists just check which words in list A also belong to the set of words in list B

In this example I gave, the output is:

['oi', 'tchaum', 'ontem', 'amanha']

Only the elements that the two lists have.

    
07.10.2017 / 17:23