- 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.
推薦閱讀
- Java 開發從入門到精通(第2版)
- 深入淺出Spring Boot 2.x
- Rust Cookbook
- Java加密與解密的藝術
- 游戲程序設計教程
- Building RESTful Python Web Services
- Java面向對象程序設計
- Building Machine Learning Systems with Python(Second Edition)
- Learning Apache Karaf
- Spring Data JPA從入門到精通
- UI動效設計從入門到精通
- 企業級Java現代化:寫給開發者的云原生簡明指南
- C/C++代碼調試的藝術
- Elastix Unified Communications Server Cookbook
- Python自動化運維:技術與最佳實踐