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

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.

主站蜘蛛池模板: 兰西县| 阿克| 宣武区| 铜山县| 通辽市| 阜城县| 宾川县| 和政县| 西城区| 安塞县| 长葛市| 蓬莱市| 肃北| 儋州市| 通海县| 佳木斯市| 康定县| 辽中县| 阳山县| 太和县| 子洲县| 灵宝市| 兰州市| 高州市| 台东市| 汝州市| 中卫市| 连云港市| 黄平县| 克拉玛依市| 五指山市| 青铜峡市| 广西| 南皮县| 鄱阳县| 司法| 乐山市| 钦州市| 浪卡子县| 双柏县| 宁陕县|