简体   繁体   中英

Count Letter Appearances in a Text File

I need to print the frequencies of each letter of a text file. Right now I'm confused on how to get the letters into an array so they are represented by a number (a-0, b-1, c-2, d-3, etc.). Then how do I count each letter without doing it individually for each one.

Sample Input (in text file):

I had a good day.

Sample Output (ellipses not included):

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. Convert all the letters into upper or lower case
  2. Put them inside a hash table with the letter as the key and the count as the value.

That's all there is to it. The complexity of the algorithm should be linearly proportional to the number of letters in the file.

After reading the file just have one string then you can count the frequency with the following code easily

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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