gpt4 book ai didi

java - 获取java中句子中最常用的两个单词

转载 作者:行者123 更新时间:2023-11-30 07:47:12 24 4
gpt4 key购买 nike

如何获取句子中最常用的两个单词,例如在计算所有单词出现的总数后,它还应该显示两个最常用的单词

import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.util.Map;
import java.util.HashMap;

public class Tokenizer

{
public static void main(String[] args)
{
int index = 0; int tokenCount; int i =0;
Map<String,Integer> wordCount = new HashMap<String,Integer>();
Map<Integer,Integer> letterCount = new HashMap<Integer,Integer>();
String message="The Quick brown fox jumps over the lazy brown dog";

StringTokenizer string = new StringTokenizer(message);


tokenCount = string.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (string.hasMoreTokens()) {
String word = string.nextToken().toLowerCase();
Integer count = wordCount.get(word);
Integer lettercount = letterCount.get(word);

if(count == null) {
wordCount.put(word, 1);
}
else {
wordCount.put(word, count + 1);
}
}
for (String words : wordCount.keySet())
{System.out.println("Word : " + words + " has count :" +wordCount.get(words));

}
}

最佳答案

遍历 HashMap,然后跟踪最高计数。

int first, second;

first = second = Integer.MIN_VALUE;

String firstWord, secondWord;

for (Map.Entry<String, Integer> entry : map.entrySet())
{

int count = entry.getValue();
String word = entry.getKey();

if (count > first)
{
second = first;
secondWord = firstWord;
first = count;
firstWord = word;
}
else if (count > second && count != first)
{
second = count;
secondWord = word;
}
}

System.out.println(firstWord + " " + first);
System.out.println(secondWord + " " + second);

关于java - 获取java中句子中最常用的两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33750489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com