Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

compare two file and find matching words in python

I have a two file: the first one includes terms and their frequency:

table 2
apple 4
pencil 89

The second file is a dictionary:

abroad
apple
bread
...

I want to check whether the first file contains any words from the second file. For example both the first file and the second file contains "apple". I am new to python. I try something but it does not work. Could you help me ? Thank you

for line in dictionary:
    words = line.split()
    print words[0]

for line2 in test:
    words2 = line2.split()
    print words2[0]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Something like this:

with open("file1") as f1,open("file2") as f2:
    words=set(line.strip() for line in f1)   #create a set of words from dictionary file

    #why sets? sets provide an O(1) lookup, so overall complexity is O(N)

    #now loop over each line of other file (word, freq file)
    for line in f2:
        word,freq=line.split()   #fetch word,freq 
        if word in words:        #if word is found in words set then print it
            print word

output:

apple

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...