编写java程序1.1把以下内容复制保存在一个文件english.txt中。 Joy in living comes from having fine emotions, trusting them, giving them the freedom of a bird in the open. Joy in living can never be assumed as a pose, or put on from the outside as a mask. People who have this joy do not need to talk about it; they radiate it. They just live out their joy and let it splash its sunlight and glow into other lives as naturally as bird sings. 1.2编写程序,读取文件english.txt的内容,输出以下内容: (1)总共出现的单词数量 (2)一共有多少个不同的单词 (3)按单词出现的频率从大到小输出单词,每行输出一个单词和数量,每一行格式如下: 单词:数量
时间: 2024-04-08 22:30:46 浏览: 38
一个java编写的程序
以下是Java程序的示例代码,用于读取文件english.txt的内容并输出要求的结果:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class WordFrequency {
public static void main(String[] args) {
// 读取文件内容
String fileName = "english.txt";
List<String> words = readFile(fileName);
// 统计单词数量
int totalWords = words.size();
System.out.println("(1) 总共出现的单词数量: " + totalWords);
// 统计不同单词数量
int uniqueWords = countUniqueWords(words);
System.out.println("(2) 一共有多少个不同的单词: " + uniqueWords);
// 统计单词频率并按照频率从大到小排序输出
Map<String, Integer> wordFrequency = countWordFrequency(words);
System.out.println("(3) 按单词出现的频率从大到小输出单词:");
printWordFrequency(wordFrequency);
}
// 读取文件内容并返回单词列表
public static List<String> readFile(String fileName) {
List<String> words = new ArrayList<>();
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String word = scanner.next().toLowerCase();
word = word.replaceAll("[^a-zA-Z]", ""); // 只保留字母
if (!word.isEmpty()) {
words.add(word);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return words;
}
// 统计不同单词数量
public static int countUniqueWords(List<String> words) {
Set<String> uniqueWords = new HashSet<>(words);
return uniqueWords.size();
}
// 统计单词频率
public static Map<String, Integer> countWordFrequency(List<String> words) {
Map<String, Integer> wordFrequency = new HashMap<>();
for (String word : words) {
wordFrequency.put(word, wordFrequency.getOrDefault(word, 0) + 1);
}
return wordFrequency;
}
// 按照频率从大到小排序并输出单词及数量
public static void printWordFrequency(Map<String, Integer> wordFrequency) {
List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(wordFrequency.entrySet());
sortedList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
for (Map.Entry<String, Integer> entry : sortedList) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
请确保将文件english.txt放在与程序相同的目录下,并运行上述代码即可得到结果。
阅读全文