【问题标题】:Use StringTokenizer to count frequency of each word使用 StringTokenizer 计算每个单词的频率
【发布时间】:2015-10-18 17:02:46
【问题描述】:

我对我的作业有几个问题。

赋值是让用户输入一个句子,程序统计每个单词的出现频率,当用户输入一个空字符串时,退出程序。此外,该程序区分大小写。例如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);

           while (st.hasMoreTokens())
            {
             List<String> sentenceElement = new ArrayList<String>();
             sentenceElement.add(st.nextToken());
            }

            System.out.println(sentenceElement);
        }
  }

我有几个问题。

  1. 我尝试将所有标记保存到一个名为 sentenceElement 的数组中,并尝试输出,但失败了。编译器显示

错误:找不到符号 System.out.println(sentenceElement);

  1. 如何计算每个词出现的频率?

非常感谢,非常感谢您的回答和解决方案。

【问题讨论】:

  • 不要使用 StringTokenizer,它是遗留的,不应再使用。引用 StringTokenizer api: StringTokenizer 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它。建议任何寻求此功能的人使用 String 的 split 方法或 java.util.regex 包。
  • 检查Scope of Local Variable Declarations。对于第 2 部分,使用Map 存储单词及其出现是个好主意
  • 以这种方式完成作业是一种糟糕的方式。 :P。请自行尝试。
  • @NinadIngole 感谢您的 cmets,我已经为此工作了两天,请到这里寻求帮助。

标签: java arrays tokenize


【解决方案1】:

您可以使用以下方法将输入转换为令牌

    String tokens[]=input.split(" ");

接下来是计算每个单词的频率。您可以为此使用 Hashmap。

HashMap < String, Integer > hmap = new HashMap < Integer, String > ();
for (str: tokens) {
    if (hmap.get(str) == null) hmap.put(str, 1);
    else hmap.put(str, hmap.get(str) + 1);
}
Iterator it = hmap.iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry) it.next();
    System.out.println(pair.getKey() + " = " + pait.getValue());
    it.remove();
}

【讨论】:

    【解决方案2】:
    1. 如何计算每个词出现的频率?

    使用 HashMap 将单词存储为键,将计数存储为值。然后循环遍历所有单词,如果返回null,首先从hashmap中获取单词作为键,然后将字母添加到hashmap中,如果相同的键进入循环,那么get of hashmap将不会返回null,它将返回旧计数,即1 不将其增加到 2 并在所有单词完成后再次将其存储回来,您的哈希图中有计数,只需迭代它并打印 key->value 。

    【讨论】:

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