本文整理汇总了Golang中bufio.NewScanner函数的典型用法代码### 示例。如果您正苦于以下问题:Golang NewScanner函数的具体用法?Golang NewScanner怎么用?Golang NewScanner使用的例子?那么恭喜您, 这里精选的函数代码### 示例或许可以为您提供帮助。

在下文中一共展示了NewScanner函数的20个代码### 示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码### 示例。

示例1: populateGridFromStdin

func populateGridFromStdin() [GRID_ROW_SIZE][GRID_COL_SIZE]int {

    var grid [GRID_ROW_SIZE][GRID_COL_SIZE]int

    i := 0

    inputScanner := bufio.NewScanner(os.Stdin)

    for inputScanner.Scan() {

        j := 0

        lineScanner := bufio.NewScanner(strings.NewReader(inputScanner.Text()))
        lineScanner.Split(bufio.ScanWords)

        for lineScanner.Scan() {

            grid[i][j], _ = strconv.Atoi(lineScanner.Text())
            j++

        }

        if j == 0 {
            break
        }

        i++
    }

    return grid
}

开发者ID:katamaritaco,项目名称:ProjectEulerPracticeProblems,代码行数:31,代码来源:problem_011.go

示例2: RecordResponse

// RecordResponse writes response's status, headers and body.
func (r *APIB) RecordResponse(resp *http.Response, status, headers, body []byte, wc io.WriteCloser) (err error) {
    indent := strings.Repeat(" ", 12)

    // indent headers
    var headersS []string
    s := bufio.NewScanner(bytes.NewReader(headers))
    for s.Scan() {
        headersS = append(headersS, indent+s.Text())
    }
    if err = s.Err(); err != nil {
        return
    }

    // indent body
    var bodyS []string
    s = bufio.NewScanner(bytes.NewReader(body))
    for s.Scan() {
        bodyS = append(bodyS, indent+s.Text())
    }
    if err = s.Err(); err != nil {
        return
    }

    err = apibResponseTemplate.Execute(wc, map[string]interface{}{
        "StatusCode": resp.StatusCode,
        "Headers":    strings.Join(headersS, "\n"),
        "Body":       strings.Join(bodyS, "\n"),
    })
    if err == nil {
        err = wc.Close()
    }
    return
}

开发者ID:go-gophers,项目名称:gophers,代码行数:34,代码来源:apib.go

示例3: MergeColumns

func MergeColumns() {
    f1, err := os.Open(COL1_FILENAME)
    if err != nil {
        log.Fatalln("open col1.txt error:", err)
    }
    defer f1.Close()
    s1 := bufio.NewScanner(f1)
    f2, err := os.Open(COL2_FILENAME)
    if err != nil {
        log.Fatalln("open col2.txt error:", err)
    }
    defer f2.Close()
    s2 := bufio.NewScanner(f2)

    mf, err := os.Create(MERGED_FILENAME)
    if err != nil {
        log.Fatalln("create merged.txt error:", err)
    }
    defer mf.Close()

    for s1.Scan() && s2.Scan() {
        c1 := s1.Text()
        c2 := s2.Text()
        fmt.Fprintf(mf, "%s\t%s\n", c1, c2)
    }
}

开发者ID:Pandaman,项目名称:natural-language-processing100-practice,代码行数:26,代码来源:main.go

示例4: LogCommand

func LogCommand(cmd *exec.Cmd, asDebug bool) {
    logrus.WithField("command", cmd.Args).Debugf("running command")
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return
    }
    stderr, err := cmd.StderrPipe()
    if err != nil {
        return
    }
    go func() {
        in := bufio.NewScanner(stdout)
        for in.Scan() {
            if asDebug {
                logrus.Debugf(in.Text())
            } else {
                logrus.Infof(in.Text())
            }
        }
    }()
    go func() {
        in := bufio.NewScanner(stderr)
        for in.Scan() {
            logrus.Debugf(in.Text())
        }
    }()
}

开发者ID:layer-x,项目名称:layerx-commons,代码行数:27,代码来源:hooks.go

示例5: runClient

func runClient(addr string) {
    conn, err := net.Dial("tcp", addr)
    if err != nil {
        log.Fatal(err)
    }

    defer conn.Close()

    // Messages from the conn to stdout.
    // The scanner will exit when the conn is closed.
    // We close the conn via the defer.
    go func() {
        s := bufio.NewScanner(conn)
        for s.Scan() {
            fmt.Fprintf(os.Stdout, s.Text()+"\n")
        }
    }()

    // Messages from stdin to the conn.
    // The scanner will exit when stdin is closed.
    // We close stdin via ctrl-D.
    s := bufio.NewScanner(os.Stdin)
    for s.Scan() {
        fmt.Fprintf(conn, s.Text()+"\n")
    }
}

开发者ID:peterbourgon,项目名称:training,代码行数:26,代码来源:main.go

示例6: readNames

func readNames(names []string) ([]string, error) {
    if len(inputFile) == 0 {
        return names, nil
    }

    var scanner *bufio.Scanner
    if inputFile != "-" {
        in, err := os.Open(inputFile)
        if err != nil {
            return nil, err
        }

        defer in.Close()
        scanner = bufio.NewScanner(in)
    } else {
        scanner = bufio.NewScanner(os.Stdin)
    }

    for scanner.Scan() {
        names = append(names, scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        return nil, err
    }

    return names, nil
}

开发者ID:ericcapricorn,项目名称:gotags,代码行数:27,代码来源:main.go

示例7: listen

func (c *Client) listen() {
    r := bufio.NewScanner(c)
    res := time.Now()
    for {
        select {
        case <-c.quit:
            c.Close()
            return

        default:
            c.SetReadDeadline(time.Now().Add(120 * time.Second))
            if !r.Scan() {
                if ne, ok := r.Err().(net.Error); ok {
                    if ne.Temporary() && ne.Timeout() && time.Since(res) < 300*time.Second {
                        r = bufio.NewScanner(c)
                        c.sout("PING %s", c.Host)
                        continue
                    }
                }
                c.err <- r.Err()
                return
            }
            c.psrv(r.Text())
            res = time.Now()
        }
    }
}

开发者ID:qeedquan,项目名称:misc_utilities,代码行数:27,代码来源:sirc.go

示例8: TestCorpus

// I actually wanted to have a test containing all the words used in the
// original paper but Martin Porter (author of the original algorithm)
// has provided a massive collection of ~23000 words with the expected
// output of the algorithm so we can test our implementation against
// the original paper implementation
func TestCorpus(t *testing.T) {
    input, errIn := os.Open("corpus/test_input.txt")
    output, errOut := os.Open("corpus/test_output.txt")

    defer input.Close()
    defer output.Close()

    if errIn != nil || errOut != nil {
        t.Fatalf("Could not read input or output test files [%s, %s]", errIn, errOut)
    }

    inScan := bufio.NewScanner(input)
    outScan := bufio.NewScanner(output)

    for inScan.Scan() && outScan.Scan() {
        in := inScan.Text()
        out := outScan.Text()
        stemmed := Stem(in)

        t.Logf("[PASS] Input: %s → Expected: %s, Stemmed: %s\n", in, out, stemmed)

        if !strings.EqualFold(out, stemmed) {
            t.Errorf("[FAIL] Expected %s but got %s for input %s\n", out, stemmed, in)
        }
    }

    if inScan.Err() != nil || outScan.Err() != nil {
        t.Fatalf("Could not open scanner for input or output test files [%s, %s]", inScan.Err(), outScan.Err())
    }
}

开发者ID:suhailpatel,项目名称:go-stemmer,代码行数:35,代码来源:stemmer_test.go

示例9: ExampleSecureConn_client

// Secure chat client
func ExampleSecureConn_client() error {
    // connect to remote server
    c, err := net.Dial("tcp", "localhost:8080")
    if err != nil {
        return err
    }
    defer c.Close()

    // wrap insecure client, perform key exchange and retrieve
    // a secured connection
    sc, err := secureconn.New(c)
    if err != nil {
        return err
    }
    defer sc.Close()

    // read messages from the server line by line
    go func() {
        scanner := bufio.NewScanner(sc)
        for scanner.Scan() {
            fmt.Println(scanner.Text())
        }
    }()

    // read messages from command line to send to server
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        _, err := sc.Write([]byte(scanner.Text() + "\n"))
        if err != nil {
            return err
        }
    }

    return nil
}

开发者ID:billyboar,项目名称:GCSolutions,代码行数:36,代码来源:example_test.go

示例10: Start

func (tm *TestKeeper) Start() error {
    if tm.cmd != nil {
        panic(fmt.Errorf("tm: %s, cmd not cleanly stopped", tm.id))
    }
    tm.cmd = exec.Command(tm.keeperBin, tm.args...)
    stdoutPipe, err := tm.cmd.StdoutPipe()
    if err != nil {
        return err
    }
    go func() {
        scanner := bufio.NewScanner(stdoutPipe)
        for scanner.Scan() {
            fmt.Printf("[%s]: %s\n", tm.id, scanner.Text())
        }
    }()

    stderrPipe, err := tm.cmd.StderrPipe()
    if err != nil {
        return err
    }
    go func() {
        scanner := bufio.NewScanner(stderrPipe)
        for scanner.Scan() {
            fmt.Printf("[%s]: %s\n", tm.id, scanner.Text())
        }
    }()
    err = tm.cmd.Start()
    if err != nil {
        return err
    }
    return nil
}

开发者ID:ksmaheshkumar,项目名称:stolon,代码行数:32,代码来源:utils.go

示例11: Load

// Creates new Trie struct loaded from filename
func Load(filename string, maxLength int) (*Trie, error) {
    file, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    cfs := make(map[rune]int)
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        w := scanner.Text()
        if maxLength < 1 || len(w) < maxLength {
            CharFreqs(&cfs, w)
        }
    }

    t := CustomNew(cfs)

    if _, err := file.Seek(0, 0); err != nil {
        return nil, err
    }

    scanner = bufio.NewScanner(file)
    for scanner.Scan() {
        w := scanner.Text()
        if maxLength < 1 || len(w) < maxLength {
            t.AddWord(w)
        }
    }

    return t, nil
}

开发者ID:postfix,项目名称:unitrie,代码行数:33,代码来源:unitrie.go

示例12: gatherCmdOutput

func gatherCmdOutput(taskName string, cmd *exec.Cmd, eventsChan chan *types.Event) error {
    stdoutReader, err := cmd.StdoutPipe()
    if err != nil {
        return err
    }

    stderrReader, err := cmd.StderrPipe()
    if err != nil {
        return err
    }

    stdoutScanner := bufio.NewScanner(stdoutReader)
    stderrScanner := bufio.NewScanner(stderrReader)
    go func() {
        for stdoutScanner.Scan() {
            eventsChan <- types.NewOutputEvent(taskName, stdoutScanner.Bytes())
        }
    }()

    go func() {
        for stderrScanner.Scan() {
            eventsChan <- types.NewOutputEvent(taskName, stderrScanner.Bytes())
        }
    }()

    return nil
}

开发者ID:xsb,项目名称:dog,代码行数:27,代码来源:executor.go

示例13: main

func main() {
    // EXAMPLE 1
    reader := StringPump("Test")

    scanner := bufio.NewScanner(reader)
    for scanner.Scan() {
        fmt.Printf("Received: %s \n", scanner.Text())
    }

    // EXAMPLE 2
    reader = Capitalize(StringPump("Test"))

    scanner = bufio.NewScanner(reader)
    for scanner.Scan() {
        fmt.Printf("Received: %s \n", scanner.Text())
    }

    // EXAMPLE 3
    ToLower := WrapStringWordFilter(strings.ToLower)
    reader = ToLower(Capitalize(StringPump("Test THIS bit")))

    scanner = bufio.NewScanner(reader)
    for scanner.Scan() {
        fmt.Printf("Received: %s \n", scanner.Text())
    }

    fmt.Printf("Finished.\n")
}

开发者ID:suntong,项目名称:lang,代码行数:28,代码来源:Piping_Pipe.go

示例14: logCmd

func (t *task) logCmd(cmd *exec.Cmd) {
    stderr, _ := cmd.StderrPipe()
    stdout, _ := cmd.StdoutPipe()

    go t.logPipe(bufio.NewScanner(stderr))
    go t.logPipe(bufio.NewScanner(stdout))
}

开发者ID:pselibas,项目名称:semaphore,代码行数:7,代码来源:logging.go

示例15: scannerFromFile

func scannerFromFile(reader io.Reader) (*bufio.Scanner, error) {

    var scanner *bufio.Scanner
    //create a bufio.Reader so we can 'peek' at the first few bytes
    bReader := bufio.NewReader(reader)

    testBytes, err := bReader.Peek(64) //read a few bytes without consuming
    if err != nil {
        return nil, err
    }
    //Detect if the content is gzipped
    contentType := http.DetectContentType(testBytes)

    fmt.Printf("Content Type:%s\n", contentType)

    //If we detect gzip, then make a gzip reader, then wrap it in a scanner
    if strings.Contains(contentType, "x-gzip") {
        gzipReader, err := gzip.NewReader(bReader)
        if err != nil {
            return nil, err
        }

        scanner = bufio.NewScanner(gzipReader)

    } else {
        //Not gzipped, just make a scanner based on the reader
        scanner = bufio.NewScanner(bReader)
    }

    return scanner, nil
}

开发者ID:dbenque,项目名称:maglogparser,代码行数:31,代码来源:main.go

示例16: ensureSlot

func ensureSlot(slots, item string) (err error) {
    fi, err := sysfs.OpenFile(slots, os.O_RDWR|os.O_APPEND, 0666)
    defer fi.Close()
    if err != nil {
        return
    }

    // ensure the slot is not already written into the capemanager
    // (from: https://github.com/mrmorphic/hwio/blob/master/module_bb_pwm.go#L190)
    scanner := bufio.NewScanner(fi)
    for scanner.Scan() {
        line := scanner.Text()
        if strings.Index(line, item) > 0 {
            return
        }
    }

    _, err = fi.WriteString(item)
    if err != nil {
        return err
    }
    fi.Sync()

    scanner = bufio.NewScanner(fi)
    for scanner.Scan() {
        line := scanner.Text()
        if strings.Index(line, item) > 0 {
            return
        }
    }
    return
}

开发者ID:ympons,项目名称:gobot,代码行数:32,代码来源:beaglebone_adaptor.go

示例17: importReader

func importReader(reader io.Reader, gzipped bool) {
    var scanner *bufio.Scanner
    if gzipped {
        gReader, err := gzip.NewReader(reader)
        if err != nil {
            log.Println("[ERR] My bad! I tried to start uncompressing your archive but failed.")
            log.Println("      Try checking the file, or send me the file so I can check it out.")
            return
        }
        defer gReader.Close()
        log.Println("[OK!] GZip detected, unzipping enabled")
        scanner = bufio.NewScanner(gReader)
    } else {
        scanner = bufio.NewScanner(reader)
    }
    log.Println("[OK!] Reading initialized")
    imported := 0
    skipped := 0
    // Now we scan ୧༼ಠ益ಠ༽୨
    for scanner.Scan() {
        status, _ := importLine(scanner.Text())
        if status {
            imported++
        } else {
            skipped++
        }
    }
    log.Println("[OK!] Reading completed")
    log.Println("      " + strconv.Itoa(imported) + " torrents imported")
    log.Println("      " + strconv.Itoa(skipped) + " torrents skipped")
}

开发者ID:unrealord,项目名称:bitcannon,代码行数:31,代码来源:import.go

示例18: main

func main() {
    d := make(map[string]string)
    for _, a := range os.Args[1:] {
        ww := strings.Split(a, ",")
        tag, fname := ww[0], ww[1]
        println(a)
        r, err := os.Open(fname)
        if err != nil {
            panic(fname)
        }
        sc := bufio.NewScanner(r)
        for sc.Scan() {
            line := sc.Text()
            GrokLine(line, tag, d)
        }

        r.Close()
    }

    r := os.Stdin
    sc := bufio.NewScanner(r)
    for sc.Scan() {
        line := sc.Text()
        tail := ""
        ww := strings.Split(line, " ")
        if len(ww) > 0 && len(ww[0]) > 0 {
            k := strings.ToUpper(ww[0])
            if v, ok := d[k]; ok {
                tail = ReplaceWhite(v, " ")
            }
        }
        Println(line + " ;; " + tail)
    }
}

开发者ID:strickyak,项目名称:doing_os9,代码行数:34,代码来源:annotate_trace.go

示例19: executeCommand

func (s Shell) executeCommand() (err error) {
    outReader, err := s.Command.StdoutPipe()
    if err != nil {
        return
    }

    errReader, err := s.Command.StderrPipe()
    if err != nil {
        return
    }

    var bufout, buferr bytes.Buffer
    outReader2 := io.TeeReader(outReader, &bufout)
    errReader2 := io.TeeReader(errReader, &buferr)

    s.Command.Start()
    outScanner := bufio.NewScanner(outReader2)
    for outScanner.Scan() {
        fmt.Println(outScanner.Text())
    }

    errScanner := bufio.NewScanner(errReader2)
    for errScanner.Scan() {
        fmt.Println("[stderr]" + errScanner.Text())
    }

    s.Command.Wait()
    return
}

开发者ID:tmknom,项目名称:aws-infrastructure,代码行数:29,代码来源:shell.go

示例20: main

func main() {
    exb := make([]byte, 0, 128*128)
    buf := bytes.NewBuffer(exb)

    f, err := os.Open("tmp.txt")
    if err != nil {
        panic(err)
    }
    s := bufio.NewScanner(f)
    start := make(chan int)
    go func() {
        <-start
        for s.Scan() {
            if s.Err() != nil {
                panic(err)
            }
            _, err := buf.WriteString(s.Text() + "\n")
            if err != nil {
                panic(err)
            }
        }
    }()

    start <- 1
    s2 := bufio.NewScanner(buf)
    for s2.Scan() {
        if err := s2.Err(); err != nil {
            panic(err)
        }
        fmt.Println("Received line:", s2.Text())
    }
}

开发者ID:samuell,项目名称:experiments,代码行数:32,代码来源:stream.go

最后编辑: goerone  文档更新时间: 2021-08-23 19:14   作者:goerone