从用户输入中找到最常用的单词

问题描述 投票:2回答:4

我是Java的新手,创建了一个软件应用程序,允许用户将文本输入到字段中,程序会遍历所有文本并识别最常用的单词。目前,我的代码如下所示:

JButton btnMostFrequentWord = new JButton("Most Frequent Word");
btnMostFrequentWord.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    String text = textArea.getText();
    String[] words = text.split("\\s+");
    HashMap<String, Integer> occurrences = new HashMap<String, Integer>();
    for (String word : words) {
      int value = 0;
      if  (occurrences.containsKey(word)) {
        value = occurrences.get(word);
      }
      occurrences.put(word, value + 1);
    }

    JOptionPane.showMessageDialog(null, "Most Frequent Word: " + occurrences.values());
  }
}

这只是打印单词的值,但我想告诉我最常见的单词是什么。任何帮助将非常感激。

java arrays sorting hashmap windowbuilder
4个回答
2
投票

for循环之后,您可以按值对地图进行排序,然后按值反转排序的条目并选择第一个。

for (String word: words) {
    int value = 0;
    if  (occurrences.containsKey(word)) {
        value = occurrences.get(word);
    }
    occurrences.put(word, value + 1);
}

Map.Entry<String,Integer> tempResult = occurrences.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .findFirst().get();
JOptionPane.showMessageDialog(null, "Most Frequent Word: " + tempResult.getKey());

0
投票

对于任何更熟悉Java的人来说,使用Java 8这是一个非常简单的方法:

List<String> words = Arrays.asList(text.split("\\s+"));

Collections.sort(words, Comparator.comparingInt(word -> {
    return Collections.frequency(words, word);
}).reversed());

排序后最常见的单词存储在words.get(0)中。


0
投票

我会做这样的事情

int max = 0;
String a = null;
for (String word : words) {
    int value = 0;
    if(occurrences.containsKey(word)){
        value = occurrences.get(word);
    }
    occurrences.put(word, value + 1);
    if(max < value+1){
        max = value+1;
        a = word;
    }
}
System.out.println(a);

你可以对它进行排序,解决方案会更短,但我认为这样运行得更快。


0
投票

您可以迭代发生地图并找到最大值或尝试如下

String text = textArea.getText();;
String[] words = text.split("\\s+");
HashMap<String, Integer> occurrences = new HashMap<>();
int mostFreq = -1;
String mostFreqWord = null;

for (String word : words) {
    int value = 0;
    if (occurrences.containsKey(word)) {
        value = occurrences.get(word);
    }
    value = value + 1;
    occurrences.put(word, value);

    if (value > mostFreq) {
        mostFreq = value;
        mostFreqWord = word;
    }
}

JOptionPane.showMessageDialog(null, "Most Frequent Word: " + mostFreqWord);
© www.soinside.com 2019 - 2024. All rights reserved.