Dkk
Dkk

Reputation: 63

Python:Comparing the strings in two files and printing the match does not works properly

I am trying to compare the strings of file "formatted_words.txt" with another customised file "dictionary.txt" and in the output I am trying to print those words from "formatted_words.txt"formatted_words file which are present in file "dictionary.txt"dictionary file.

from itertools import izip
with open("formatted_words.txt") as words_file:
    with open("dictionary.txt") as dict_file:
        all_strings = list(map(str.strip,dict_file))
        for word in words_file:
            for a_string in all_strings:
               if word in a_string:
                  print a_string 

Nevertheless, in the output, all the words of the file "formatted_words.txt" are getting printed, though many words from this file are not in the "dictionary.txt".I cannot use any builtin python dictionary.Any help would be appreciated.

Upvotes: 0

Views: 37

Answers (1)

kaidokuuppa
kaidokuuppa

Reputation: 642

Using sets:

with open('formatted_words.txt') as words_file:
    with open('dictionary.txt') as dict_file:
         all_strings = set(map(str.strip, dict_file))
         words = set(map(str.strip, words_file))
         for word in all_strings.intersection(words):
             print(word)

Prints nothing because the intersection is empty

Upvotes: 1

Related Questions