繁体   English   中英

计算文本文件中的字母出现次数

[英]Count Letter Appearances in a Text File

我需要打印文本文件中每个字母的频率。 现在我很困惑如何将字母放入数组中,以便用数字表示(a-0、b-1、c-2、d-3 等)。 那么我如何计算每个字母而不单独计算每个字母。

示例输入(在文本文件中):

我过了愉快的一天。

样品 Output(不包括椭圆):

a-3 b-0 c-0 d-3... g-1 h-1 i-1... o-2... y-1 z-0

/*
 * 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.


    Scanner fileScan = new Scanner(new File(filename));  //another Scanner to open and read the file
    //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


    }
    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


  }
}
  1. 将所有字母转换为大写或小写
  2. 将它们放在 hash 表中,其中字母为键,计数为值。

这里的所有都是它的。 算法的复杂度应该与文件中的字母数量成线性比例。

读取文件后只有一个字符串,然后您可以使用以下代码轻松计算频率

Map<Character, Long> freq = Arrays.stream(arr).
            collect(Collectors.groupingBy(Character::charValue, Collectors.counting()));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM