简体   繁体   中英

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.

Is there a better way of doing this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM