Нахождение частоты каждой буквы в текстовом файле - PullRequest
0 голосов
/ 11 ноября 2019

Я пытаюсь распечатать частоту каждой буквы, найденной в текстовом файле. Я не уверен, как это зациклить и правильно получить массив, чтобы делать то, что я хочу. У меня есть основы, но я потерян. Есть идеи?

Пример текстового файла:

Здравствуйте, меня зовут Захари. Взятие людей рентгеновским снимком - это то, чем я занимаюсь.

Желаемый результат:

Буквы - Частоты в файле:

a - 7

b- 0

c - 1

d - 1

e - 4

f - 1

g - 2

ч - 3

i - 6

j - 0

k - 1

л - 4

м -2

n - 3

o - 4

p - 2

q - 0

r - 2

s - 3

t - 2

u - 0

v - 1

w - 1

x - 1

y - 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));

  }
}
}

1 Ответ

1 голос
/ 11 ноября 2019

Помните, что тип char - это число в Java, так что если у вас есть массив, размер которого равен 26, вы можете увеличить нужный элемент, сказав myArray[line.charAt(i) - 'a']++;

Также обратите внимание, что циклдолжны проходить через буквы в строке, а не через массив.

Когда вы хотите напечатать буквы, просмотрите массив и получите правильную букву из индекса с обратным вычислением: если ваш индексв переменной i соответствующая буква равна i + 'a', а ее частота равна myArray[i].

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...