对于给定的文件sample.txt,统计其中单词的个数,以及给定单词出现的次数。用java实现
时间: 2023-11-27 09:50:05 浏览: 66
这份代码中包括探究矩阵和统计单词出现的次数
以下是Java实现代码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static void main(String[] args) {
String fileName = "sample.txt"; // 文件名
String[] wordsToCount = {"apple", "banana", "orange"}; // 要统计的单词
int totalWordCount = 0; // 单词总数
Map<String, Integer> wordCounts = new HashMap<>(); // 存储单词出现次数的Map
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split("\\s+"); // 以空格为分隔符切分单词
for (String word : words) {
totalWordCount++;
if (wordCounts.containsKey(word)) {
wordCounts.put(word, wordCounts.get(word) + 1);
} else {
wordCounts.put(word, 1);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Total word count: " + totalWordCount);
for (String word : wordsToCount) {
int count = wordCounts.containsKey(word) ? wordCounts.get(word) : 0;
System.out.println(word + ": " + count);
}
}
}
```
代码解释如下:
1. 定义文件名和要统计的单词数组;
2. 定义单词总数和存储单词出现次数的Map;
3. 使用BufferedReader逐行读取文件,并以空格为分隔符切分出单词;
4. 统计单词总数和每个单词的出现次数,存储到Map中;
5. 输出单词总数和每个指定单词的出现次数。
阅读全文