首页 > 解决方案 > 查找文本文件中每个字母的频率

问题描述

我正在尝试打印在文本文件中找到的每个字母的频率。我不知道如何循环这个并正确地得到一个数组来做我想做的事。我有基础知识,但我迷路了。有任何想法吗?

示例文本文件:

你好,我的名字是扎卡里。拍摄人们的 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));

  }
}
}

标签: javaarraysloops

解决方案


请记住,charJava 中的类型是数字,因此如果您有一个大小为 26 的数组,您可以通过说myArray[line.charAt(i) - 'a']++;

另请注意,循环应该通过行中的字母,而不是通过数组。

当您要打印字母时,通过数组并通过相反的计算从索引中获取正确的字母:如果您的索引在 variable 中i,则对应的字母是i + 'a'并且它的频率是myArray[i]


推荐阅读