Pythonhelp1323
Pythonhelp1323

Reputation: 25

Comparing two files to print a line that matches a word

I have two text files one like this

dog cat fish

and another file like this

The cat ran The fish swam The parrot sang

I'm looking to be able to search through the second text file and print the lines that contain the words from the first text file, for example, the output for this would be

The cat ran The fish swam

Upvotes: 1

Views: 665

Answers (1)

astiktyagi
astiktyagi

Reputation: 26

What about something like this. We take key words from first file and store them then while reading second file we refer them before printing

# file1.txt
# dog
# cat
# fish

# file2.txt
# The cat ran
# The fish swam
# The parrot sang

# reading file1 and getting the keywords
with open("file1.txt") as f:
    key_words = set(f.read().splitlines())

# reading file2 and iterating over all read lines 
with open("file2.txt") as f:
    all_lines = f.read().splitlines()
    for line in all_lines:
        if any(kw in line for kw in key_words): # if any of the word in key words is in line print it
            print(line)

Upvotes: 1

Related Questions