从多个点扫描文件

我有一个文件abc.txt,其中包含打印两次的字母表,并用换行符分隔

abcdefghijklmopqrstuvwxyz
abcdefghijklmopqrstuvwxyz

我想创建一个可以同时解析行的解析器。例如,每行一个 goroutine。我当前尝试执行此操作的流程是:

  • 创建一个通道来接收文本行

  • 为每行创建一个新的扫描仪

  • 将扫描仪和通道传递给 goroutine

  • 主进程中的处理结果

然而,只有一台扫描仪返回有用的输出。我想做的代码是这样的:

func main() {

    file, err := os.Open("./strangeness/abc.txt")

    if err != nil {

        log.Panic(err)

    }

    defer file.Close()


    inChan := make(chan string)


    for i := 0; i < 2; i++ {

        var scanner scanner.Scanner

        file.Seek(27, 0)


        scanner.Init(file)


        go parseLine(fmt.Sprintf("Scanner %v:", i), &scanner, inChan)

    }


    for msg := range inChan {

        fmt.Println(msg)

    }

}


func parseLine(name string, scanner *scanner.Scanner, out chan string) {

    for i := 0; i < 26; i++ {

        out <- fmt.Sprintf("%s %c", name, scanner.Next())

    }

}

我想我可能对 go 的text/scanner工作原理或文件的一般工作原理有一些误解,但我无法追踪错误的实际来源。


潇潇雨雨
浏览 103回答 1
1回答

杨__羊羊

该问题似乎是由于 2 个文件扫描仪同时移动头部所致。可以通过创建 2 个文件句柄(每个句柄都有自己的扫描仪)来实现所需的结果。以下对我有用package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "os"&nbsp; &nbsp; "text/scanner"&nbsp; &nbsp; "time")func main(){&nbsp; &nbsp; var file [2]*os.File&nbsp; &nbsp; var err error&nbsp; &nbsp; file[0], err = os.Open("./abc.txt")&nbsp; &nbsp; file[1], err = os.Open("./abc.txt")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer file[0].Close()&nbsp; &nbsp; defer file[1].Close()&nbsp; &nbsp; var scanner [2]scanner.Scanner&nbsp; &nbsp; inChan := make(chan string)&nbsp; &nbsp; for i := 0; i < 2; i++ {&nbsp; &nbsp; &nbsp; &nbsp; var n int64 = (int64)(i) * 26&nbsp; &nbsp; &nbsp; &nbsp; file[i].Seek(n, 0)&nbsp; &nbsp; &nbsp; &nbsp; scanner[i].Init(file[i])&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(scanner[0].Pos)&nbsp; &nbsp; &nbsp; &nbsp; go parseLine(fmt.Sprintf("Scanner %v:", i), &scanner[i], inChan)&nbsp; &nbsp; }&nbsp; &nbsp; for msg := range inChan {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(msg)&nbsp; &nbsp; }}func parseLine(name string, scanner *scanner.Scanner, out chan string) {&nbsp; &nbsp; for i := 0; i < 26; i++ {&nbsp; &nbsp; &nbsp; &nbsp; out <- fmt.Sprintf("%s %c", name, scanner.Next())&nbsp; &nbsp; }&nbsp; &nbsp; time.Sleep(time.Second * 10)&nbsp; &nbsp; close(out)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go