1

I'm trying to split (variable) output restext into individual sentences (delimiters are '.', '?' and '!' for this exercise), and print only the first sentence (i.e. take output restext, look for first occurrence of either '.', '?' or '!' and print the first full sentence). Without the use of external libraries

I've tried

printtext = restext.replace('?',' ').replace('!',' ').replace('.',' ').split()
print(printtext);

For example:

restext = "Hello my dear! How have you been? I was wondering how you are. Do let me know how you are!"

I will get

[Hello, my, dear, How, have, you, been, I, was, wondering, how, you, are, Do, let, me, know, how, you, are]

But I'm looking for

"Hello my dear!"

1 Answer 1

2

One way to achieve this is to replace each sentence ending character with itself plus another character that won't be in the text, for example #. Then you can split on that character to get the individual sentences:

restext = "Hello my dear! How have you been? I was wondering how you are. Do let me know how you are!"
sentences = restext.replace('?','?#').replace('!','!#').replace('.','.#').split('#')
printtext = sentences[0]
print(printtext)

Output:

Hello my dear!
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.