'print the number of sentences from a string [duplicate]
def number_of_sentences_in(text):
text = sentence.split()
return len(text.split())
text = "She stopped. Turned around. Oops, a bear. Just like that."
print(number_of_sentences_in(text))
Hello everyone,
I have to implement a code that has a output of 4, because the text above has 4 sentences. How do I edit this code, so the output is 4.
Solution 1:[1]
Maybe you could just count how many periods (.) are there using str.count instead of splitting, so you don't have to deal with the extra empty string ('') corresponding to the part after the final period when using text.split('.'):
def get_number_of_sentences(text: str) -> int:
return text.count('.')
text = 'She stopped. Turned around. Oops, a bear. Just like that.'
print(f'{text = }')
number_of_sentences = get_number_of_sentences(text)
print(f'{number_of_sentences = }')
For a more robust approach, that can handle other forms of punctuation indicating sentence endings, you could use nltk.sent_tokenize:
import nltk
def get_number_of_sentences(text: str) -> int:
return len(nltk.sent_tokenize(text))
text = 'She stopped. Turned around. Oops, a bear. Just like that.'
print(f'{text = }')
number_of_sentences = get_number_of_sentences(text)
print(f'{number_of_sentences = }')
Output:
text = 'She stopped. Turned around. Oops, a bear. Just like that.'
number_of_sentences = 4
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
