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

  • Go Systems Programming
  • Mihalis Tsoukalos
  • 180字
  • 2021-07-02 18:08:02

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.

主站蜘蛛池模板: 石狮市| 肇庆市| 仁寿县| 保亭| 乃东县| 天津市| 文山县| 桃江县| 通州区| 安福县| 通江县| 水富县| 涞源县| 炉霍县| 满城县| 西充县| 门源| 西平县| 赤水市| 泽库县| 贵州省| 仁化县| 林芝县| 花莲县| 新平| 台东县| 喜德县| 山阳县| 抚宁县| 墨竹工卡县| 萍乡市| 荣成市| 施甸县| 西昌市| 禹州市| 宕昌县| 鄯善县| 香港| 乡城县| 汕头市| 宜兴市|