字母频率

Letter Frequency

我有一个任务,用户需要在其中输入一个字符串,到目前为止,我的程序会打印出它出现的次数,但我还需要显示字母的频率,例如,如果我要输入"ab" - 它会显示 字母出现频率 1 0.5 b 1 0.5

任何帮助将不胜感激

提前致谢

import java.io.*;

public class ProgrammingAsignment {

public static void main (String [] args)throws IOException
{
    BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter Any Text:");
    String output = BR.readLine();
    output=output.toLowerCase();
    int length = output.length();
    char character;

    System.out.println("Letters\tFrequency\tCount");

    int count = 0;
    for(char i ='a'; i<='z'; i++)
    {
        count = 0;
        for(int j=0; j<length; j++)
        {
            character = output.charAt(j);
            if(character==i)
                count++;
        }
        if(count!=0)
        {
            System.out.println(i+"\t\t"+count);
        }
      }
    }

  }

将每个字母的计数保存在一个数组中。要获得任何字母的频率,请将其计数除以所有字母的计数总和。

最好的解决方案是构建一个大小为 26(从 a 到 z 的字符数)或 52(如果需要区分大小写)或 128(如果需要映射所有 ascii字符)。 例如:

int[] counter = new int[128];

在你的字符之间循环并为每个元素加 1。 例如,如果您找到 A 字母,则必须这样做:

counter[(int) 'A']++;

或者更一般,如果 ch 是当前字符:

counter[(int) ch]++; 

最后您将获得计算频率所需的所有数据。

您的代码现在打印出 Occurs。因此,要执行频率,请在外部 for 循环中添加一个新变量,例如 sum_count。在每个内部 for 循环迭代结束时,将 count 的值添加到 sum_count,如下所示:

int sum_count = 0;
for(char i ='a'; i<='z'; i++)
{
        int count = 0;
        for(int j=0; j<length; j++)
        {
            character = output.charAt(j);
            if(character==i)
                count++;
        }
        sum_count += count; 
      ...
 }

现在,对于每个字母,只计算出现次数的值,即 count,然后除以 sum_count

System.out.println(i+"\t\t"+count+"\t\t"+sum_count/count);

我会使用正则表达式

   public CountFrequency wordString(String word, String input){
        String regex = "\b" + word;
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input); 
        int count = 0;

        while(m.find()){
         count++;
        }

        if(count =< 0){
            return new CountFrequency(0, 0.0);          
        }
        return new CountFrequency(count, (double)input.size()/count);       
   }




class CountFrequency{
        private int count = 0;
        private double frequency = 0.0;

        public CountFrequency(int count, double frequency){
            this.count = count;
            this.frequency = frequency;
        }

        int getCount(){
            return count;
        }

        double getFrequency(){
            return frequency;
        }
   }

这是一个使用地图存储遇到的字母并为遇到的每个字母保持最新计数的示例。一张图让你事先不知道输出中会遇到多少不同的字符。

package lettercount;
import java.util.*;
import java.io.*;

//Version that demonstrates using a map to keep a running count for items encountered
//This way you only have to step through the input once.
public class ProgrammingAssignment {

public static void main(String[] args) throws IOException {
    BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter Any Text: ");
    String output = BR.readLine();
    output=output.toLowerCase();

    int length = output.length();
    char character;
    int totalCount = 0;

    //we'll store each encountered character in this map, along with a count of the number
    //of times encountered.
    Map<Character, Integer> map = new HashMap<Character,Integer>();

    //Loop over the output once, character by character
    for (int i = 0; i < length; i++)
    {
        character = output.charAt(i);
        totalCount++; //This is the total number of characters we've found in the output

        Integer countForCharacter = 0;
        //check in map if we have a count for this character
        if (map.containsKey(character)) {
            //get the current count we have for this character
            countForCharacter = map.get(character);
            //increment
            countForCharacter++;
            //increment the count
        } else {
            countForCharacter = 1;
        }

        //Now put the up to date count into the map
        map.put(character, countForCharacter);
    }


    //Get the found characters as an array of Character
    Character[] charactersFound = map.keySet().toArray(new Character[0]);

    System.out.println("Letters\tFrequency\tCount");
    for(int k = 0; k < charactersFound.length; k++)
    {
        character = charactersFound[k];
        System.out.println(character+
                "\t" +
                //Following line gets the count for the character and divides by totalCount,
                //making sure that the the result is a floating point
                (map.get(character)/((float)totalCount)) +
                "\t"+
                //get the count for the character
                map.get(character));
    }
}

}