相对频率Java中文本文件中字母(a-z)的计数

时间:2013-11-21 21:53:11

标签: java

我的文本输入文件已经处理过,只包含字母(a-z)和空格。出于某种原因,当我输入一个非常大的文本文件(大约400 000个单词文件,通过切割和粘贴到MSWord中确定)时,相对频率计数失败。但是对于较小的文件,它可以工作,例如总字符= 36。请有人能告诉我代码出错的地方吗?

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class SoloCount {

public static void main(String[] args) throws IOException {
String inputFile = "sampleOutput.txt";


// My array for the a-z (97-122, based on ASCII table )

try {
int[] myArray = new int[26];
BufferedReader readerObject = new BufferedReader(new FileReader(inputFile));
String sCurrentLine="";
sCurrentLine = readerObject.readLine();

for(int i = 0; i<sCurrentLine.length(); i++)  // for each character in the readline                    from the input file, a-z will be counted.
        {
            if (Character.isLetter(sCurrentLine.charAt(i)) == true)     // qualifies characterisa letter and not an empty space.
            {
            char singleLetter = sCurrentLine.charAt(i);
            myArray[(int)(singleLetter)-97] = myArray[(int)(singleLetter)-97] + 1;  // Assigning frequency of a character. 97-122 represents a-z (ASCII table). e.g lowercase c = 97
            }
        }
        readerObject.close();


    //Calculate the total number of characters from the input file.
    double sumOfCharacters= 0;
    for (int i = 0; i < myArray.length; i++) 
    {
        sumOfCharacters += myArray[i];
    }
    System.out.println("The total number of characters in this file is: " + sumOfCharacters);

    //Calculating the realtive frequency.  Divide each occurrence for each letter (a-z) by the sumOfCharacters.
    System.out.printf("%10s%6s%n", "Letter", "%");   //column labels "Letter" and "%"
    System.out.println();
    for (int i = 0; i < myArray.length; i++) 
    {
        char singleLetter = (char)(i + 97);         //converting the decimal ASCII annotation to letters for a-z
        double value = myArray[i];
        System.out.printf("%8s%13f%n",singleLetter,(value/sumOfCharacters)*100);
    }

    } 
catch (FileNotFoundException e) {
        e.printStackTrace();
    }


}

}

1 个答案:

答案 0 :(得分:1)

您只读取文件的一行 - 可能是该行只有36个字符,或者36个字符后面有换行符。

您还可以通过传入更大的初始缓冲区大小来增加BufferedReader的缓冲区大小 -

BufferedReader readerObject = new BufferedReader(new FileReader(inputFile), 2048);

有关详细信息,请参阅here