【问题标题】:How to count frequency of each words in the array?如何计算数组中每个单词的频率?
【发布时间】:2015-10-19 00:37:14
【问题描述】:

我有一个程序,用户可以输入一个句子,它可以将每个单词分成一个数组。另外,我需要计算每个单词的频率。例如,Apple is an apple is a phone,结果是Apple-1;是-2;一个-1;一个-1;电话 1

请帮我解决这个问题,我不知道如何计算每个单词的频率。

这是我的代码:

  public static void main(String[] args)
  {
  while (true)
  {
        System.out.println("Enter a sentence:");
        Scanner keyboard = new Scanner(System.in);
        String sentence = keyboard.nextLine();

        if (sentence.isEmpty())      // quit the program when user enter an empty string
        {
           break;
        }
        else
        {
        StringTokenizer st = new StringTokenizer(sentence);

        List<String> sentenceElement = new ArrayList<String>();

        while (st.hasMoreTokens())
        {
          sentenceElement.add(st.nextToken());
        }

        System.out.println(sentenceElement);
        }
  }

非常感谢!!

【问题讨论】:

  • 你为什么要使用无限循环?
  • 当用户输入一个空字符串时,退出程序。
  • 这个问题来自here。在那个问题中,有一个实现HashMap 的答案。你试过了吗?

标签: java count


【解决方案1】:

您可以使用HashMap,单词为Key,出现次数为Value

public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);
    String[] myPhrase = keyboard.nextLine().split(" ");
    HashMap<String, Integer> myWordsCount = new HashMap<String, Integer>();
    for (String s : myPhrase){
        if (myWordsCount.containsKey(s)) myWordsCount.replace(s, myWordsCount.get(s) + 1);
        else myWordsCount.put(s, 1);
    }
    System.out.println(myWordsCount);
}

输出

One two three four and again three and four
{four=2, and=2, One=1, again=1, two=1, three=2}

【讨论】:

  • 谢谢!您的解决方案非常适合我!
  • @wei 不客气。不要忘记接受和投票:) 会很好。
【解决方案2】:

获取字符串数组后,您可以从 Java 10 开始尝试以下代码。它使用流来获取频率图。

import java.util.Arrays;
import java.util.stream.Collectors;

public class StringFrequencyMap {
    public static void main(String... args) {
        String[] wordArray = {"Apple", "is", "an", "apple", "is", "a", "phone"};
        var freqCaseSensitive = Arrays.stream(wordArray)
                         .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
        //If you want case insensitive then use
        var freqCaseInSensitive = Arrays.stream(wordArray)
                .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));

        System.out.println(freqCaseSensitive);
        System.out.println(freqCaseInSensitive);
    }
}

输出:

{a=1, apple=1, Apple=1, phone=1, is=2, an=1}
{a=1, apple=2, phone=1, is=2, an=1}

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2014-03-13
    • 2015-06-06
    相关资源
    最近更新 更多