java统计abc.txt文件中的单词数,行数,每个字符出现的百分比。并将结果写入result.txt文件中
时间: 2023-11-22 19:55:39 浏览: 81
下面是一个Java程序,可以实现你所需要的功能:
```java
import java.io.*;
import java.util.*;
public class FileStats {
public static void main(String[] args) {
String inputFile = "abc.txt";
String outputFile = "result.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
int wordCount = 0;
int lineCount = 0;
Map<Character, Integer> charCounts = new HashMap<>();
String line;
while ((line = reader.readLine()) != null) {
lineCount++;
// Split the line into words
String[] words = line.split("[^a-zA-Z]+");
for (String word : words) {
if (!word.isEmpty()) {
wordCount++;
// Count the characters in the word
for (char c : word.toCharArray()) {
charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);
}
}
}
}
// Write the results to the output file
writer.write(String.format("Word count: %d\n", wordCount));
writer.write(String.format("Line count: %d\n", lineCount));
writer.write("Character counts:\n");
for (Map.Entry<Character, Integer> entry : charCounts.entrySet()) {
char c = entry.getKey();
int count = entry.getValue();
double percent = ((double) count / wordCount) * 100;
writer.write(String.format("%c: %d (%.2f%%)\n", c, count, percent));
}
System.out.println("Results written to " + outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该程序使用了Java的文件输入输出库,以及Java的集合框架。它的思路是先读取输入文件的每一行,然后将每一行拆分成单词,再统计单词数和每个字符出现的次数。最后将结果写入输出文件。
你只需要将程序中的 `abc.txt` 和 `result.txt` 替换成你自己的文件名,即可使用。
阅读全文