java - 查找文本文件中每个字母的频率
问题描述
我正在尝试打印在文本文件中找到的每个字母的频率。我不知道如何循环这个并正确地得到一个数组来做我想做的事。我有基础知识,但我迷路了。有任何想法吗?
示例文本文件:
你好,我的名字是扎卡里。拍摄人们的 X 光片是我谋生的工作。
期望的输出:
信件 - 文件中的频率:
一 - 7
b - 0
c - 1
d - 1
e - 4
f - 1
克 - 2
h - 3
我 - 6
j - 0
k - 1
l - 4
米 - 2
n - 3
o - 4
p - 2
q - 0
r - 2
小号 - 3
t - 2
你 - 0
v - 1
w - 1
x - 1
是 - 3
z - 1
/*
* program that reads in a text file and counts the frequency of each letter
* displays the frequencies in descending order
*/
import java.util.*; //needed for Scanner
import java.io.*; //needed for File related classes
public class LetterCounter {
public static void main(String args[]) throws IOException{
Scanner keyboard = new Scanner(System.in); //Scanner to read in file name
System.out.println("Enter the name of the text file to read:");
String filename = keyboard.next();
//This String has all the letters of the alphabet
//You can use it to "look up" a character using alphabet.indexOf(...) to see what letter it is
//0 would indicate 'a', 1 for 'b', and so on. -1 would mean the character is not a letter
String alphabet = "abcdefghijklmnopqrstuvwxyz";
//TODO: create a way to keep track of the letter counts
//I recommend an array of 26 int values, one for each letter, so 0 would be for 'a', 1 for 'b', etc.
int[] myArray = new int[26];
Scanner fileScan = new Scanner(new File(filename)); //another Scanner to open and read the file
char letterFind = fileScan.nextLine().charAt(0);
//loop to read file line-by-line
while (fileScan.hasNext()) { //this will continue to the end of the file
String line = fileScan.nextLine(); //get the next line of text and store it in a temporary String
line = line.toLowerCase( ); // convert to lowercase
//TODO: count the letters in the current line
int letter = 0;
for (int i=0; i<myArray.length; i++) {
char current = line.charAt(i);
if (letterFind == current) {
letter++;
}
}
fileScan.close(); //done with file reading...close the Scanner so the file is "closed"
//print out frequencies
System.out.println("Letters - Frequencies in file:");
//TODO: print out all the letter counts
System.out.println(line.charAt(letter));
}
}
}
解决方案
请记住,char
Java 中的类型是数字,因此如果您有一个大小为 26 的数组,您可以通过说myArray[line.charAt(i) - 'a']++;
另请注意,循环应该通过行中的字母,而不是通过数组。
当您要打印字母时,通过数组并通过相反的计算从索引中获取正确的字母:如果您的索引在 variable 中i
,则对应的字母是i + 'a'
并且它的频率是myArray[i]
。
推荐阅读
- r - 在 R 中,我抓取了一张表格。现在,当我提取它的值时,它们是 NA。我可以将它们转换为数字吗?
- sql - 符号名称是“id”期望的
- android - 带有动态功能指南的即时动态功能
- javascript - 如何通过 Javascript 设置多个模式的样式
- c++ - 这个 C++ 片段中的缓冲区溢出在哪里?
- c# - 在 ASP.NET Core Entity Framework 中编辑期间尝试自动递增计数器
- angular - 从 API 获取 Angular 中的图像 url
- amazon-web-services - 保险丝:未找到设备,在 docker 容器上安装 s3 存储桶时先尝试“modprobe fuse”
- windows - 运行时加载同一目录(不是应用程序目录)中的 DLL
- flutter - 如何向具有图像的容器添加突出显示颜色?