首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WordCount方法

WordCount方法
EN

Stack Overflow用户
提问于 2015-11-18 01:33:25
回答 1查看 187关注 0票数 0

我不明白为什么我的代码不能工作。我得到一个错误:“找不到符号方法数组()”,它是在getLength类中定义的。对如何改进这种方法有什么建议吗?谢谢!

代码语言:javascript
复制
/**
     * getWordCount
     * 
     * Get a count of how many times each word occurs in an input String.
     * 
     * @param text a string containing the text you wish to analyze
     * @return a map containing entries whose keys are words, and
     *         whose values correspond to the number of times that word occurs
     *         in the input String text.
     */
    public Map<String,Integer> getWordCount(String text)
    {
         String[] parts = text.trim().split("('s|\\W)+"); 

        Map<String, Integer> wordCountMap = new TreeMap<String, Integer>();
        for(int i=0;i<parts.getLength();i++)
        {
            for(String text : parts[i].toString())
            {
                if(!wordCountMap.containsKey(text))
                {
                     wordCountMap.put(text,1);
                } else {
                    int freq = wordCountMap.get(text);
                    freq++;
                    wordCountMap.put(text,freq);
                }
                return wordCountMap;
            }
            return new TreeMap<String,Integer>();
        } 
    }
EN

回答 1

Stack Overflow用户

发布于 2015-11-18 02:00:37

您的代码存在多个问题。

以下更改可能会有所帮助

代码语言:javascript
复制
public Map<String,Integer> getWordCount(String text)
{
    String[] parts = text.trim().split("('s|\\W)+"); 

    Map<String, Integer> wordCountMap = new TreeMap<String, Integer>();
    for (String part : parts)
    {
        if(!wordCountMap.containsKey(part))
        {
             wordCountMap.put(part,1);
        } else {
            int freq = wordCountMap.get(part);
            freq++;
            wordCountMap.put(part,freq);
        }
    }
    return wordCountMap;
}

下面的测试代码给出了一个大小为5的代码,它似乎确认了你在代码中想要做的事情。

代码语言:javascript
复制
Map<String, Integer> map = getWordCount(" the fox jumped over the moon ");
System.out.println("size:" + map.size());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33763417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档