yishairasowsky
yishairasowsky

Reputation: 831

how do i get the sentence in a document containing a particular word using python?

From an entire text, I want to extract the whole sentence in which a given word appears. For example:

text = "The cat ran. I am Sam. Whoop dee doo."
output = get_sentence("am")

Should yield --> "I am Sam."

Upvotes: 0

Views: 590

Answers (3)

Taksh
Taksh

Reputation: 78

You can use nltk library to tokenize the sentence

nltk.download("punkt")
text = "Hello, I am Taksh. Nice to meet you Mr. Panchal. 
                    You scored 82.5 % in test"
nltk.tokenize.sent_tokenize(text)
>> ['Hello, I am Taksh.',
    'Nice to meet you Mr. Panchal.',
    'You scored 82.5 % in test']

Upvotes: 1

Dev
Dev

Reputation: 387

text = "The cat ran. I am Sam. Whoop dee doo."
text =  text.split('.')
data = input("Enter the String want to search")
for i in text:
   if data in i:
      print(i )
   else:
      print("search word is not present")

Upvotes: 0

clubby789
clubby789

Reputation: 2713

Split the string into sentences then search each for the phrase

text = text.split('. ')
for s in text:
    if searchWord in s:
        return s + "."
    return "Search word not found"

Upvotes: 0

Related Questions