官术网_书友最值得收藏!

Finding the number of occurrences

A very common programming problem is finding out the number of times an IP address appears in a log file. So, the example in this subsection will show you how to do this using a handy map structure. The occurrences.go program will be presented in three parts.

The first part is as follows:

package main 
 
import ( 
   "fmt" 
   "strings" 
) 
 
func main() { 
 
   var s [3]string 
   s[0] = "1 b 3 1 a a b" 
   s[1] = "11 a 1 1 1 1 a a" 
   s[2] = "-1 b 1 -4 a 1" 

The second part is as follows:

   counts := make(map[string]int) 
 
   for i := 0; i < len(s); i++ { 
         data := strings.Fields(s[i]) 
         for _, word := range data { 
               _, ok := counts[word] 
               if ok { 
                     counts[word] = counts[word] + 1 
               } else { 
                     counts[word] = 1 
               } 
         } 
   } 

Here, we use the knowledge from the previous chapter to create a map named counts and populate it with the desired data using two for loops.

The last part is pretty small as it just prints the contents of the counts map:

   for key, _ := range counts {

fmt.Printf("%s -> %d \n", key, counts[key]) } }

Executing occurrences.go and using the sort(1) command-line utility to sort the output of occurrences.go will generate the following kind of output:

$ go run occurrences.go | sort -n -r -t\  -k3,3
1 -> 8
a -> 6
b -> 3
3 -> 1
11 -> 1
-4 -> 1
-1 -> 1

As you can see, traditional Unix tools are still useful.

主站蜘蛛池模板: 潞西市| 卫辉市| 永丰县| 大港区| 晋州市| 永丰县| 闽侯县| 滨州市| 上饶县| 琼海市| 江安县| 新建县| 青冈县| 盐山县| 富源县| 松江区| 金乡县| 河间市| 沁水县| 五家渠市| 永登县| 苏尼特右旗| 襄樊市| 杨浦区| 呼和浩特市| 天祝| 兴文县| 巴林左旗| 呼和浩特市| 勃利县| 大理市| 大英县| 商水县| 临沧市| 聊城市| 宁乡县| 平阳县| 曲靖市| 垦利县| 宜宾县| 军事|