Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a sentence with an exact word not as a part of the other word

I need to find all sentences with exact word match. Not inside of the other words.

I’m trying this:
text='He's using apple phone. I like apples. Did you install this app? Apply today!'

[sentence + '.' for sentence in text.split('.') if 'app' in sentence]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I get the output:
'He's using apple phone. I like apples. Did you install this app? Apply today!'

but need only:
Did you install this app?

>Solution :

To find all sentences with an exact word match, you can use word boundaries in your search query. In Python, you can use the re module to search for regular expressions.

import re

text = "He's using apple phone. I like apples. Did you install this app? Apply today!"

# Use regex to find sentences with the exact word "app"
pattern = r'\bapp\b'
matches = re.findall(pattern, text)

# Split the text into sentences and only keep the ones with a match
sentences = text.split('.')
result = [sentence.strip() + '.' for sentence in sentences if re.search(pattern, sentence)]

print(result)

This code should output [‘Did you install this app?’]

Note that we’re using the re.search method instead of in to search for the word "app" with word boundaries (\b). This ensures that we only match the exact word and not words that contain "app" as a substring.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading