Java中的单词计数类不计算出现的每个“那个”

时间:2019-02-18 20:02:52

标签: java

我正在尝试用Java创建一个哈希表类,该类对出现的每个单词进行计数。它在大多数情况下都有效,但是当我尝试使用以下段落时:

  

“他们给婴儿取名为苏珊(Susan)。那个经理发现盒子空了。唐娜(Donna)的女儿把门打开了。那个音乐家发现这本书很有趣。那个牙医叫那只狗叫费多(Fido)”。

它会检测除“ That”以外的所有其他单词的正确数量。 “那个”在该段落中出现了3次,但仅检测到一个“那个”。这是代码:

import java.util.*;

public class WordCounts extends ConsoleProgram
{
    public void run()
    {
        HashMap<String,Integer> h = new HashMap<String,Integer>();
        String input = readLine("Enter a string: ");
        String[] words = input.split(" ");
        for(int i=0; i<words.length; i++)
        {
            Integer num = h.get(words[i]);
            if( num == null)
                num = new Integer(1);
            else
                num = new Integer(num.intValue() + 1);

            h.put(words[i].toLowerCase(), num);
        }

        printSortedHashMap(h);
    }

    /*
     * This method takes a HashMap of word counts and prints out
     * each word and it's associated count in alphabetical order.
     *
     * @param wordCount The HashMap mapping words to each word's frequency count
     */
    private void printSortedHashMap(HashMap<String, Integer> wordCount)
    {
        // Sort all the keys (words) in the HashMap
        Object[] keys = wordCount.keySet().toArray();
        Arrays.sort(keys);

        // Print out each word and it's associated count
        for (Object word : keys) 
        {
            int val = wordCount.get(word);
            System.out.println(word + ": " + val);
        }
    }
}

如果有人可以提供帮助,我将不胜感激。预先感谢。

编辑:我不小心在描述中写了“ that”而不是“ That”;我的意思是,我试图弄清楚为什么班级没有计算每个“那个”。

4 个答案:

答案 0 :(得分:1)

可能有很多事情... 如果您不使用ignoreCase(),则在Java眼中,“ that”和“ that”是不同的。 另外,请尝试使用StringTokenizer格式化字符串,这将使您的生活更轻松,代码也更短。

答案 1 :(得分:1)

这里的主要问题是由以下几行引起的:

h.get(words[i])

 h.put(words[i].toLowerCase(), num)

您正在寻找HashMap中单词的原始大小写,但将它们存储为小写形式。因此,当您第一次看到“ That”时,您将其添加为“ that”。下次您看到“那个”,瞧,它不在您的地图中!因为Java区分大小写,并且将“ That”和“ that”视为不同的字符串。因此,您将“ that”重新添加到地图中,值为1。冲洗并为看到的每个重复的“ That”重复。

您可能想做的是在开始之前将整个输入字符串都小写。您可能还希望删除所有标点符号,以便句子结尾的单词不包含句点。

答案 2 :(得分:0)

您需要像保存它一样检查小写的字符串键。

Integer num = h.get(words[i].toLowerCase());

此外,您还需要在split方法中更改正则表达式以仅获取单词:

String[] words = input.split("[ ,.?!:;]");

答案 3 :(得分:0)

为代码内联检出注释,以更新字符串数组中的字数。

buff <- st_transform(buff, crs = 4326)

library(leaflet)

leaflet() %>% 
  addTiles() %>% 
  addMeasure(primaryLengthUnit = "meters") %>% 
  addMarkers(data = pois) %>% 
  addPolygons(data = buff)