Seminix
Seminix

Reputation: 97

How to search for multiple keywords in a textfile in Python

Lets say keywords1.txt contains the following:

Broken Screen

Then I write this program:

sentence = input("Input your sentence: ")
if open('keywords1.txt').read() in sentence:
    print("hello there")

I wanted it to display 'hello there' whenever i say for example: my screen is broken

But it doesn't work. Putting those wods in a textfile as a list still doesn't work:

Broken
Screen

Upvotes: 1

Views: 139

Answers (3)

nino_701
nino_701

Reputation: 692

You can use the set method issubset to do that:

sentence = input("Input your sentence: ")
A = open('keywords1.txt').read().split('\n') # or any other separator
B = sentence.split()
A, B = set(A), set(B)  

if A.issubset(B) :
    print("hello there")

Upvotes: 0

Wuelfhis Asuaje
Wuelfhis Asuaje

Reputation: 51

Check re module

Maybe a re.match or re.find

Regards

Upvotes: 1

Walter_Ritzel
Walter_Ritzel

Reputation: 1397

Here is a basic algorithm for that. Maybe there is some function in python to make it easy, but this is the most basic code.

sentence = input("Input your sentence: ")
findCount = 0
lines = 0
fLines = open('keywords1.txt').readlines()
for line in fLines:
    lines += 1
    if line in sentence:
       findCount += 1
if lines == findCount:
   print("hello there")

Upvotes: 1

Related Questions