Groovy高效编程——统计单词频率

摘要Groovy横空出世,她几乎兼容Java的所有语法,Groovy至少已经具备了继承未来主流语言王位的必要条件--语言本身是利用当前主流语言所编写,并与当前主流语言的语法相似,且能够结束当前主流语言的弊病。

搜索引擎,语音识别等领域常会统计单词的出现频率,下面给出Groovy实现,打印出现频率最高的6个单词以及相应的出现次数:

 

 def content    =   
     """
    The Java Collections API is the basis   for   all the nice support that Groovy gives you
    through lists and maps. In fact,Groovy not only uses the same abstractions,it
    even works on the very same classes that make up the Java Collections API.
     """
 
def words  =  content.tokenize()

def wordFrequency  =  [:]

words.each {
    wordFrequency[it]  =  wordFrequency.get(it,0 )  +   1  
} 

def wordList  =  wordFrequency.keySet().toList()

wordList.sort {wordFrequency[it]} 

def result  =   ''  

wordList[ - 1 .. - 6 ].each {
    result  +=  it.padLeft( 12 )  +   " :  "   +  wordFrequency[it]  +   "  /n  "  
} 
 
println result  

运行结果:

 

             the: 5
   Groovy: 2
          that: 2
 Collections: 2
         Java: 2
        same: 2   

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...