计算java中wordList的字母频率

时间:2018-04-16 18:04:40

标签: java

如何计算java中wordList的字母频率。

所有单词都存储在wordList ARRAYLIST中!      *你需要遍历每个单词和      *计算wordList中所有单词的字母频率      * @return一个整数的ArrayList。第一个要素是a的频率,      *第二个元素是b的频率,依此类推。      *示例:      *如果wordList有[" cat"," dog"," turtle"]      * freq() - >返回的arraylist值:[1,0,1,1,1,0,1,0,0,0,0,1,0,0,1,0,0,1,0,3,1,0,0 ,0,0,0]      *返回的arraylist中的每个数字代表每个字母出现的次数      * in wordsList arraylist(a:1,b:0,c:1 .... so on)      * * / public ArrayList freq(){

    String s = "abcdefghijklmnopqrstuwxvz";

       char[] c = s.toCharArray();
       int sz =c.length;
       int  i =0, j=0 , counter=0;

       for( i=0; i<sz; i++) {
           for( j=0; j<sz; ++j) {

        if(c[j] == c[i]) {
            counter++;
        }
       }
return

       }    
    return null;
}

1 个答案:

答案 0 :(得分:0)

import java.util.*;

public class LetterFrequency 
{
    static final String alphabet    = "abcdefghijklmnopqrstuvwxyz";
    static final char[] alphabetArr = alphabet.toCharArray();
    static final int    NUM_LETTERS = 26;

    public static void main(String argv[]) // test it
    {
        System.out.println("alphbetArr.length = " + alphabetArr.length);
        ArrayList<String> words = new ArrayList<String>();
        words.add("Hello"); words.add("World"); words.add("This"); words.add("Test"); words.add("Works!");
        printResults(getFrequency(words));
    }

    public static int[] getFrequency(ArrayList<String> wordList)
    {
        int[] ret          = new int[NUM_LETTERS];

        for (int i=0; i < wordList.size(); i++)
        {
            String word = wordList.get(i).toLowerCase();
            String len = word.length();
            for (int j=0; j < NUM_LETTERS; j++)
                for(int k=0; k < len; k++)
                    if (alphabetArr[j] == word.charAt(k))
                        ret[j]++
        }
        return ret;
    }

    public static void printResults(int[] freq)
    { for (int i =0; i < freq.length; i++) System.out.print("frequency[" + alphabetArr[i] + "=" + freq[i] + "], "); }
}