【问题标题】:Count Letter Appearances in a Text File计算文本文件中的字母出现次数
【发布时间】:2019-11-08 00:09:55
【问题描述】:

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

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

我度过了愉快的一天。

示例输出(不包括省略号):

a-3 b-0 c-0 d-3 ... g-1 h-1 我-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


  }
}

【问题讨论】:

    标签: java arrays algorithm


    【解决方案1】:
    1. 将所有字母转换为大写或小写
    2. 将它们放在一个哈希表中,以字母为键,计数为值。

    仅此而已。算法的复杂度应该与文件中的字母数量成线性比例。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这位OP似乎是编程或Java的初学者。重点是学习算法是如何工作的,而不是学习如何使用Streams 来抛出函数链,这对于有经验的人来说似乎是干净的代码,但对于新手来说,绝对是阅读的噩梦。他们中的大多数人甚至不会尝试理解各个函数的作用,而是复制粘贴完成它,恭喜,一个新的复制粘贴程序员诞生了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      相关资源
      最近更新 更多