Closed. This question needs details or clarity。它当前不接受答案。
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
4年前关闭。
分词然后计算单词出现的次数
例如:“快棕色狐狸快”
预期产量:
-1
快速-2
棕色-1
狐狸-1
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
4年前关闭。
分词然后计算单词出现的次数
例如:“快棕色狐狸快”
预期产量:
-1
快速-2
棕色-1
狐狸-1
public class Tokenizer
{
public static void main(String[] args)
{
int index = 0; int tokenCount;
String words[] = new String [50];
String message="The Quick brown fox the";
StringTokenizer string = new StringTokenizer(message);
tokenCount = string.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (string.hasMoreTokens())
{ words[index] = string.nextToken(); index++; }
for (index=0;index<tokenCount; index++)
{ System.out.println(words[index]); }
}
}
最佳答案
您需要在此处使用java.util.Map
来维护单词和相应的计数:
import java.util.Map;
import java.util.HashMap;
public class Tokenizer
{
public static void main(String[] args)
{
int index = 0; int tokenCount;
Map<String,Integer> wordCount = new HashMap<String,Integer>();
String message="The Quick brown fox the";
StringTokenizer string = new StringTokenizer(message);
tokenCount = string.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (string.hasMoreTokens()) {
String word = string.nextToken();
Integer count = wordCount.get(word);
if(count == null) { //this means the word was encountered the first time
wordCount.put(word, 1);
}
else { //word was already encountered we need to increment the count
wordCount.put(word, count + 1);
}
}
for (String words : wordCount.keySet())
{ System.out.println("Word : " + word + " has count :" +wordCount.get(word);
}
}
}