定义类实现,输入一段英文段落,统计段落中出现的英文单词个数,不同英文单词个数,每个英文单词出现的次数;使用String,ArrayList完成相应功能;
时间: 2023-09-07 19:12:49 浏览: 59
好的,以下是用Java语言实现的代码:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class WordCounter {
private String paragraph;
public WordCounter(String paragraph) {
this.paragraph = paragraph;
}
public int getTotalWords() {
String[] words = paragraph.split("[^a-zA-Z]+");
return words.length;
}
public int getDistinctWords() {
ArrayList<String> distinctWords = new ArrayList<>();
String[] words = paragraph.split("[^a-zA-Z]+");
for (String word : words) {
if (!distinctWords.contains(word)) {
distinctWords.add(word);
}
}
return distinctWords.size();
}
public Map<String, Integer> getWordFrequencies() {
Map<String, Integer> wordFrequencies = new HashMap<>();
String[] words = paragraph.split("[^a-zA-Z]+");
for (String word : words) {
if (wordFrequencies.containsKey(word)) {
int count = wordFrequencies.get(word);
wordFrequencies.put(word, count + 1);
} else {
wordFrequencies.put(word, 1);
}
}
return wordFrequencies;
}
public static void main(String[] args) {
String paragraph = "This is a test paragraph. It contains some duplicate words like this, and also some unique words.";
WordCounter wordCounter = new WordCounter(paragraph);
System.out.println("Total words: " + wordCounter.getTotalWords());
System.out.println("Distinct words: " + wordCounter.getDistinctWords());
System.out.println("Word frequencies:");
Map<String, Integer> wordFrequencies = wordCounter.getWordFrequencies();
for (Map.Entry<String, Integer> entry : wordFrequencies.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
这个类接受一个英文段落作为参数,提供了三个方法来获取该段落中的单词总数、不同单词数以及每个单词出现的次数。使用了String的split方法将段落按照非字母字符分割成单词数组,然后使用ArrayList和HashMap来处理单词列表和单词出现次数的统计。在main方法中,我们对一个测试段落进行了测试。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)