duanchui1279 2016-06-25 08:28
浏览 11
已采纳

使用扫描程序每行多个令牌的更好方法?

I'm trying to parse a file with lines that consist of a key, a space, a number and then a newline.

My code works, but it doesn't smell right to me. Is there a better way to use Scanner? Particularly, I don't like having the Scan() inside the for-loop without any protection on it.

func TestScanner(t *testing.T) {
    const input = `key1 62128128

key2 8337182720

key3 7834959872

key4 18001920

key5 593104896
`
    scanner := bufio.NewScanner(strings.NewReader(input))
    scanner.Split(bufio.ScanWords)
    for scanner.Scan() {
        key := scanner.Text()
        scanner.Scan()
        value := scanner.Text();
        fmt.Printf("k: %v, v: %v
", key, value)
    }
}
  • 写回答

2条回答 默认 最新

  • dongyongyin5339 2016-06-25 08:46
    关注

    you should not use in input, and always check for errors.
    working sample code:

    package main
    
    import (
        "bufio"
        "fmt"
        "strings"
    )
    
    func main() {
        const input = `key1 62128128
    key2 8337182720
    key3 7834959872
    key4 18001920
    key5 593104896`
        scanner := bufio.NewScanner(strings.NewReader(input))
        scanner.Split(bufio.ScanWords)
        for scanner.Scan() {
            key := scanner.Text()
            if !scanner.Scan() {
                break
            }
            value := scanner.Text()
            fmt.Printf("k: %v, v: %v
    ", key, value)
        }
    }
    

    output:

    k: key1, v: 62128128
    k: key2, v: 8337182720
    k: key3, v: 7834959872
    k: key4, v: 18001920
    k: key5, v: 593104896  
    

    Also you may use Fscan which scans to desired type, like this:

    package main
    
    import "fmt"
    import "strings"
    
    func main() {
        const input = `key1 62128128
    key2 8337182720
    key3 7834959872
    key4 18001920
    key5 593104896`
        rdr := strings.NewReader(input)
        for {
            k, v := "", 0
            n, _ := fmt.Fscan(rdr, &k, &v)
            if n != 2 {
                //fmt.Println(err)
                break
            }
            fmt.Printf("%T: %[1]v, %T: %[2]v
    ", k, v)
        }
    }
    

    output:

    string: key1, int: 62128128
    string: key2, int: 8337182720
    string: key3, int: 7834959872
    string: key4, int: 18001920
    string: key5, int: 593104896
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测