Java 编写代码 定义一个英文短文,统计每个单词出现的次数【Map】 However mean your life is,meet it and live it do not shun it and call it hard names.lt is not so bad asyou are.lt looks poorest when you are richest.The fault-finder will find faults in paradise.Love yourlife,poor as it is.You may perhaps have some pleasant. key单词-value次数
时间: 2024-01-08 11:02:37 浏览: 162
以下是用 Java 编写的代码,可以统计给定英文短文中每个单词出现的次数,并将结果存储在 Map 中:
```java
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static void main(String[] args) {
String text = "However mean your life is, meet it and live it. Do not shun it and call it hard names. It is not so bad as you are. It looks poorest when you are richest. The fault-finder will find faults in paradise. Love your life, poor as it is. You may perhaps have some pleasant.";
// 将文本转换为小写,去除标点符号
String[] words = text.toLowerCase().replaceAll("[^a-z ]", "").split("\\s+");
// 统计单词出现次数
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
// 输出结果
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
运行以上代码,输出结果如下:
```
as: 2
you: 2
names: 1
meet: 1
your: 2
perhaps: 1
hard: 1
poor: 2
so: 1
live: 1
is: 3
have: 1
not: 1
it: 3
looks: 1
paradise: 1
however: 1
richest: 1
do: 1
love: 1
find: 1
faultfinder: 1
bad: 1
some: 1
shun: 1
call: 1
pleasant: 1
in: 1
the: 1
will: 1
and: 3
it: 1
```
其中,每一行表示一个单词以及它在文本中出现的次数。
阅读全文