java - 计算不同单词的数量

标签 java text-processing

我正在尝试使用 Java 计算文本中不同单词的数量。

单词可以是 unigram, bigram or trigram noun .这三个已经通过使用Stanford POS tagger找到了。 ,但我无法计算频率大于等于一、二、三、四和五的单词及其计数。

最佳答案

我可能没有正确理解,但如果您需要做的只是计算给定文本中不同单词的数量,具体取决于您从文本中获取所需单词的位置/方式,您可以使用Java.Util.Scanner 然后将单词添加到 ArrayList 并且如果单词已经存在于列表中,则不要添加它,然后列表的大小将是Distinct 单词的数量,如下例所示:

public ArrayList<String> makeWordList(){
    Scanner scan = new Scanner(yourTextFileOrOtherTypeOfInput);
    ArrayList<String> listOfWords = new ArrayList<String>();

       String word = scan.next(); //scanner automatically uses " " as a delimeter
       if(!listOfWords.contains(word)){ //add the word if it isn't added already
            listOfWords.add(word);
    }

    return listOfWords; //return the list you made of distinct words
}

public int getDistinctWordCount(ArrayList<String> list){
    return list.size();
}

现在,如果您实际上必须先计算单词中的字符数,然后再将其添加到列表中,那么您只需要添加一些语句来检查单词字符串的长度,然后再将其添加到列表中。例如:

if(word.length() <= someNumber){
//do whatever you need to
}

对不起,如果我不理解这个问题,只是给出了一些蹩脚的无关答案 =P,但我希望它在某种程度上有所帮助!

如果您需要跟踪您看到同一个单词的频率,即使您只想计算一次,您可以创建一个变量来跟踪该频率并将其放入一个列表中,以便索引频率计数与 ArrayList 中的索引相同,因此您知道频率也对应哪个词或更好地使用 HashMap 其中键是不同的词,值是它的频率(基本上使用与上面相同的代码,但使用 HashMap 代替 ArrayList 并添加一些变量来计算频率:

 public HashMap<String, Integer> makeWordList(){
        Scanner scan = new Scanner(yourTextFileOrOtherTypeOfInput);
        HashMap<String, Integer> listOfWords = new HashMap<String, Integer>();
        Scanner scan = new Scanner(sc);
        while(cs.hasNext())
       {
            String word = scan.next(); //scanner automatically uses " " as a delimeter
            int countWord = 0;
            if(!listOfWords.containsKey(word))
            {                             //add word if it isn't added already
                listOfWords.put(word, 1); //first occurance of this word
            }
            else
            {
                countWord = listOfWords.get(word) + 1; //get current count and increment
                //now put the new value back in the HashMap
                listOfWords.remove(word); //first remove it (can't have duplicate keys)
                listOfWords.put(word, countWord); //now put it back with new value
            }
       }
        return listOfWrods; //return the HashMap you made of distinct words
    }

public int getDistinctWordCount(HashMap<String, Integer> list){
       return list.size();
}

//get the frequency of the given word
public int getFrequencyForWord(String word, HashMap<String, Integer> list){
    return list.get(word);
}

关于java - 计算不同单词的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6454348/

相关文章:

Java:如果用户输入不是单个字母小写字母,我如何将用户返回到主菜单?

python - 从文件中提取特定的行集

java - 从 Java 中的另一个线程更新 JTextField

java - 如何确定 MDB 的 messageType 接口(interface)

java - 使用 Gson 解析不同 JSON 对象的列表

java - 有一个版本列表作为文件夹,想要找到最高版本

perl - 读取固定宽度数据时保留空白列并添加分隔符

regex - 如何让 "grep -zoP"分别显示每个匹配项?

python - 以 'e'结尾的英语动词处理

linux - Awk:删除行中最后一个空格后的文本