Home > Back-end >  python how to find all word matches between two text files
python how to find all word matches between two text files

Time:12-10

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.

Is there a better way of doing this?

CodePudding user response:

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