How to count repeated words number in a Sentence
Posted By : Pankaj Kumar Yadav | 18-Jun-2015
Lets have a sentence 'That that exists exists in that that that that exists exists in' and we need to find the occurence of top words. So just we pass the string in the below
method and we can get the occurence of words.
def getTopWord(String sentence){ Listkeywords = sentence.split("\\s+") // whitespace regex List resultData = new ArrayList() Map topwords = new HashMap () keywords.each{String word-> if(topwords.containsKey(word.toLowerCase())){ topwords.put(word.toLowerCase(), topwords.get(word.toLowerCase()) + 1) }else{ topwords.put(word.toLowerCase(),1) } } Map sortedMap = topwords.sort { a, b -> b.value <=> a.value } // for sorting by top occurence sortedMap.each{key, value -> Map data = new HashMap() data.word = key data.occurence = value resultData.add(data) } log.debug'All Data '+resultData }
The output will be as [[occurence:6,word:that], [occurence:4,word:exists], [occurence:2,word:in]]
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pankaj Kumar Yadav
Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.