需要用到的包,bufio
想要查看test.txt有多少行重复的并打印出来,test.txt内容如下:
111
111
111
4444
22
4444
341
99992
2222
111
4444
//dup1.go内容
package main
import (
"bufio"
"fmt"
"os"
)
//打印文件中重复出现的行,以重复次数开头,map,bufio
//执行方法:dos也是用管道: type test.txt|dup1.exe
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
counts[input.Text()]++
}
for line, num := range counts {
if num > 1 {
fmt.Printf("%d\t%s\n", num, line)
}
}
}
执行:
C:\Users\IsBean\GolandProjects\go_learning\main>go build dup1.go
C:\Users\IsBean\GolandProjects\go_learning\main>type test.txt|dup1.exe
3 4444
4 111

该博客介绍了一个使用Go语言编写的程序,该程序读取名为test.txt的文件,通过bufio包扫描文件内容,并利用map统计各行出现的次数。程序会找出并打印出所有重复的行及其出现的次数。示例文件test.txt包含一些重复的行,如'111'和'4444',程序成功地检测并显示了这些重复项。

被折叠的 条评论
为什么被折叠?



