Compute the first statistics of any NLP project for one line of text.
What to build
A program that counts the characters, letters, words and sentences in a line of text.
Requirements
- Characters: every character of the line, spaces included. Letters: characters for which
isalpha()is true. - Words: the pieces you get by splitting on whitespace.
- A sentence ends at each
.,!or?that is the last character of the line or is followed by a space (so3.14does not end a sentence, butDr.does). - Print
characters: N,letters: N,words: Nandsentences: Non four lines.
Input
One line of text.
Output
Four lines.
Constraints
The line has at most 1,000 characters.
Example
Input:
Hi there. How are you?
Output:
characters: 22
letters: 16
words: 5
sentences: 2
Why it works
Counting units is the start of every text pipeline, and the sentence rule shows why splitting text is harder than it looks: a full stop inside a number is not a sentence end, but the simple rule still cannot tell an abbreviation from the end of a sentence.
Examples
Hi there. How are you?
characters: 22 letters: 16 words: 5 sentences: 2
Wait... what?!
characters: 14 letters: 8 words: 2 sentences: 2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
`len(text)` counts characters, `text.split()` gives the words, and `ch.isalpha()` is true for letters.
Hint 2
A mark ends a sentence when it is the last character or the next character is a space: `i + 1 == len(text) or text[i + 1] == " "`.
Solution
Show one correct solution (try it yourself first)
text = input()
sentences = 0
for i, ch in enumerate(text):
if ch in ".!?" and (i + 1 == len(text) or text[i + 1] == " "):
sentences += 1
print("characters:", len(text))
print("letters:", sum(1 for ch in text if ch.isalpha()))
print("words:", len(text.split()))
print("sentences:", sentences)