extract a sentence that contains a list of keywords or phrase using python
<p>I have used the following code to extract a sentence from file(the sentence should contain some or all of the search keywords)</p>

<pre><code>search_keywords=['mother','sing','song']
with open('text.txt', 'r') as in_file:
    text = in_file.read()
    sentences = text.split(".")

for sentence in sentences:
    if (all(map(lambda word: word in sentence, search_keywords))):
        print sentence
</code></pre>

<p>The problem with the above code is that it does not print the required sentence if one of the search keywords do not match with the sentence words. I want a code that prints the sentence containing some or all of the search keywords. It would be great if the code can also search for a phrase and extract the corresponding sentence.</p>

<p>So you want to find sentences that contain at least one keyword. You can use <a href="https://docs.python.org/3/library/functions.html?highlight=any#any" rel="nofollow">any()</a> instead of <a href="https://docs.python.org/3/library/functions.html?highlight=all#all" rel="nofollow">all()</a>.</p>

<p>EDIT:
If you want to find the sentence which contains the most keywords:</p>

<pre><code>sent_words = []
for sentence in sentences:
    sent_words.append(set(sentence.split()))
num_keywords = [len(sent &amp; set(search_keywords)) for sent in sent_words]

# Find only one sentence
ind = num_keywords.index(max(num_keywords))
# Find all sentences with that number of keywords
ind = [i for i, x in enumerate(num_keywords) if x == max(num_keywords)]
</code></pre>

python file search text