Your task today is to create a program that counts the total number of words in a given sentence or paragraph. Word counting is one of the simplest and most useful text-processing operations and has applications in everything from basic text analysis to advanced natural language processing (NLP).
For example:
"The quick brown fox jumps over the lazy dog"
9 words
This task introduces you to string processing and teaches you how to:
" Hello world "
).""
)."Hello, world!"
).# Get input from the user
text = input("Enter a sentence or paragraph: ")
# Split the text into words
words = text.split()
# Count the number of words
word_count = len(words)
# Output the result
print("Word count:", word_count)
import re
# Get input from the user
text = input("Enter a sentence or paragraph: ")
# Clean the text by removing punctuation and splitting into words
words = re.findall(r'\b\w+\b', text)
# Count the number of words
word_count = len(words)
# Output the result
print("Word count:", word_count)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a sentence or paragraph: ");
String text = scanner.nextLine();
// Split the text into words
String[] words = text.trim().split("\\s+");
// Count the number of words
int wordCount = words.length;
// Output the result
System.out.println("Word count: " + wordCount);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a sentence or paragraph: ");
String text = scanner.nextLine();
// Remove punctuation and split into words
text = text.replaceAll("[^a-zA-Z0-9 ]", "").trim();
String[] words = text.split("\\s+");
// Count the number of words
int wordCount = words.length;
// Output the result
System.out.println("Word count: " + wordCount);
}
}
// Get input from the user
let text = prompt("Enter a sentence or paragraph:");
// Split the text into words
let words = text.trim().split(/\s+/);
// Count the number of words
let wordCount = words.length;
console.log("Word count:", wordCount);
// Get input from the user
let text = prompt("Enter a sentence or paragraph:");
// Remove punctuation and split into words
let words = text.replace(/[^\w\s]/g, "").trim().split(/\s+/);
// Count the number of words
let wordCount = words.length;
console.log("Word count:", wordCount);
0
." "
should also return 0
."Hello world"
) should still return the correct count.In Day 18: Find Unique Words, you’ll expand your string manipulation skills by identifying and counting unique words in a sentence or paragraph. This task builds on today’s work and introduces the concept of data deduplication!