2020年2月1日土曜日

開発環境

入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 4(コレクション)、LESSON 19(守備範囲が広いマップ)の練習問題の解答を求めてみる。

コード

package main

import (
 "fmt"
 "strings"
)

func wordCounts(s string) map[string]int {
 counts := make(map[string]int)
 for _, v := range strings.Fields(s) {
  v = strings.Trim(v, ",.?!")
  v = strings.ToLower(v)
  counts[v]++
 }
 return counts
}
func main() {
 s := `As far as eye could reach he saw nothing but the stems of the great plants about him receding in the violet shade, and far overhead the multiple transparency of huge leaves filtering the sunshine to the solemn splendour of twilight in which he walked. Whenever he felt able he ran again; the ground continued soft and springy, covered with the same resilient weed which was the first thing his hands had touched in Malacandra. Once or twice a small red creature scuttled across his path, but otherwise there seemed to be no life stirring in the wood; nothing to fear—except the fact of wandering unprovisioned and alone in a forest of unknown vegetation thousands or millions of miles beyond the reach or knowledge of man.`
 counts := wordCounts(s)

 for word, count := range counts {
  if count >= 2 {
   fmt.Printf("%v: %v回出現\n", word, count)
  }
 }
}

入出力結果(Zsh、PowerShell、Terminal)

% go run ./words.go 
as: 2回出現
reach: 2回出現
a: 2回出現
the: 12回出現
his: 2回出現
far: 2回出現
he: 4回出現
and: 3回出現
but: 2回出現
which: 2回出現
or: 3回出現
nothing: 2回出現
of: 7回出現
in: 5回出現
to: 3回出現
%

0 コメント:

コメントを投稿