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

Question:

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]

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?

Asked By: Ann Che

||

Answers:

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'bappb'
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.


split text into sentences ending with ‘.’, ‘?’, and ‘!’, you can use the regular expression module in Python to specify a pattern that matches the end of a sentence.

import re

text = "Hello! How are you? I'm fine. Thank you for asking."

# Split the text into sentences
sentences = re.split(r'(?<=[.?!])s+', text)

# Print each sentence
for sentence in sentences:
    print(sentence)

this code, we use the re.split() function to split the text into sentences. The regular expression r'(?<=[.?!])s+’ matches any whitespace character (s+) that follows a period, question mark, or exclamation point ((?<=[.?!])). This ensures that we split the text into sentences that end with any of these punctuation marks.

Answered By: bugs dev
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.