统计英文段落中每个单词出现的次数java
时间: 2023-11-24 14:07:52 浏览: 166
java 分析英文文章,并统计每个字母出现的次数
以下是实现该功能的Java代码:
```java
import java.util.HashMap;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个英文段落:");
String paragraph = scanner.nextLine();
scanner.close();
// 将段落转换为小写并去除标点符号
paragraph = paragraph.toLowerCase().replaceAll("[^a-z ]", "");
// 将单词分割并存入数组中
String[] words = paragraph.split(" ");
// 使用HashMap统计每个单词出现的次数
HashMap<String, Integer> countMap = new HashMap<>();
for (String word : words) {
if (countMap.containsKey(word)) {
countMap.put(word, countMap.get(word) + 1);
} else {
countMap.put(word, 1);
}
}
// 输出结果
System.out.println("单词出现次数统计结果:");
for (String word : countMap.keySet()) {
System.out.println(word + ": " + countMap.get(word));
}
}
}
```
运行程序后输入一个英文段落,程序会将段落转换为小写并去除标点符号,然后统计每个单词出现的次数并输出结果。例如,输入以下段落:
```
The quick brown fox jumps over the lazy dog. The dog is not amused.
```
程序将输出以下结果:
```
单词出现次数统计结果:
over: 1
dog: 2
brown: 1
not: 1
quick: 1
jumps: 1
is: 1
lazy: 1
the: 2
fox: 1
amused: 1
```
阅读全文