我正在尝试使用 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/