1

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

  • You have to show what you have done so far. Just saying about your goal is not enough. – Mans Apr 24 '20 at 15:02
  • You should share code or at least the approach you plan to use. There may be several unknowns that we might not know of while helping you. HINT: if first file contains only words keep them in a `set` – mad_ Apr 24 '20 at 15:05
  • Recommend to search existing solution before posting a question, this one seems similar -https://stackoverflow.com/questions/33103648/compare-string-in-2-differents-files-python – VN'sCorner Apr 24 '20 at 15:12
  • Pls show what u have tried so far – skaul05 Apr 24 '20 at 16:05

1 Answers1

1

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)
astiktyagi
  • 26
  • 3