First they ignore you
          then they ridicule you
          then they fight you
          then you win
              -- Mahatma Gandhi
          Chinese => English     英文 => 中文             
          隨筆-221  評論-1047  文章-0  trackbacks-0
          在搜索引擎,語音識別等領(lǐng)域常會統(tǒng)計單詞的出現(xiàn)頻率,下面給出Groovy實現(xiàn),打印出現(xiàn)頻率最高的6個單詞以及相應(yīng)的出現(xiàn)次數(shù):

          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?



          運行結(jié)果:

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

          ?


          如果所要處理的文本比較復雜,可以使用Regex進行處理,順便說一句,Groovy在語言級別支持Regex!

          posted on 2007-02-01 23:31 山風小子 閱讀(4349) 評論(6)  編輯  收藏 所屬分類: Groovy & Grails
          主站蜘蛛池模板: 台中县| 新余市| 河曲县| 汝州市| 望奎县| 罗江县| 嘉荫县| 平凉市| 博乐市| 阿尔山市| 江都市| 雷州市| 涪陵区| 吉隆县| 宣威市| 都江堰市| 石屏县| 合水县| 昂仁县| 兰州市| 保靖县| 桐城市| 休宁县| 吉木萨尔县| 铜川市| 微山县| 翼城县| 来宾市| 宣城市| 祁连县| 五常市| 红河县| 滦南县| 武胜县| 阿拉尔市| 安图县| 铜鼓县| 新化县| 平舆县| 思南县| 井陉县|