golang 一行一行读文件

来源:互联网 发布:雪梨淘宝店名叫什么 编辑:程序博客网 时间:2024/06/05 20:49
package mainimport (        "bufio"        "fmt"        "os")func main() {        counts := make(map[string]int)        files := os.Args[1:]        if len(files) == 0 {                countLines(os.Stdin, counts)        } else {                for _, arg := range files {                        f, err := os.Open(arg)                        if err != nil {                                fmt.Fprintf(os.Stderr, "dup2: %v\n", err)                                continue                        }                        countLines(f, counts)                        f.Close()                }        }        for line, n := range counts {                fmt.Printf("%d\t%s\n", n, line)        }}func countLines(f *os.File, counts map[string]int) {        input := bufio.NewScanner(f)        for input.Scan() {                counts[input.Text()]++        }        // NOTE: ignoring potential errors from input.Err()}


go run main.go a.txt


另一种方法:

package mainimport ("fmt""io/ioutil""os""strings")func main() {counts := make(map[string]int)for _, filename := range os.Args[1:] {data, err := ioutil.ReadFile(filename)if err != nil {fmt.Fprintf(os.Stderr, "dup3: %v\n", err)continue}for _, line := range strings.Split(string(data), "\n") {counts[line]++}}for line, n := range counts {if n > 1 {fmt.Printf("%d\t%s\n", n, line)}}}




0 0
原创粉丝点击