Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python how to find all word matches between two text files

I have two text files comprised of around 370k words each, one word per line. One of the files is a list of English words and the other is a list of random gibberish words. I basically want to check if any of the random words are in fact real words, so I want to compare every line in one file with every line in the other file.

I’ve tried the following:

f1 = open("file1.txt", "r")
f2 = open("file2.txt", "r")
for line in f1:
    if line in f2:
        print(line)

and this gives me about 3 results before the program inexplicably ends without an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a better way of doing this?

>Solution :

For what i understood you want the intersection of both lists, you can try this:

f1 = open("file1.txt", "r")
f2 = open("file2.txt", "r")

print(set(f1.readlines()).intersection(f2.readlines()))

f1.close()
f2.close()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading