douxie7738 2017-10-26 10:53 采纳率: 0%
浏览 271
已采纳

GoLang在字节片的第N行获取字符串

In a personal project I am implementing a function that returns a random line from a long file. For it to work I have to create a function that returns a string at line N, a second function that creates a random number between 0 and lines in file. While I was implementing those I figured it may be more efficient to store the data in byte slices by default, rather than storing them in separate files, which have to be read at run time.

Question: How would I go about implementing a function that returns a string at a random line of the []byte representation of my file.

My function for getting a string from a file:

func atLine(n int) (s string) {
    f, err := os.Open("./path/to/file")
    if err != nil {
        panic("Could not read file.")
    }
    defer f.Close()
    r := bufio.NewReader(f)
    for i := 1; ; i++ {
        line, _, err := r.ReadLine()
        if err != nil {
            break
        }
        if i == n {
            s = string(line[:])
            break
        }
    }
    return s
}

Additional info:

  • Lines are not longer than 50 characters at most
  • Lines have no special characters (although a solution handling those is welcome)
  • Number of lines in the files is known and so the same can be applied for []byte
  • 写回答

2条回答 默认 最新

  • douzhuo6270 2017-10-26 11:19
    关注

    Dealing with just the question part (and not the sanity of this) - you have a []byte and want to get a specific string line from it - the bytes.Reader has no ReadLine method which you will have already noticed.

    You can pass a bytes reader to bufio.NewReader, and gain the ReadLine functionality you are trying to access.

    bytesReader := bytes.NewReader([]byte("test1
    test2
    test3
    "))
    bufReader := bufio.NewReader(bytesReader)
    value1, _, _ := bufReader.ReadLine()
    value2, _, _ := bufReader.ReadLine()
    value3, _, _ := bufReader.ReadLine()
    fmt.Println(string(value1))
    fmt.Println(string(value2))
    fmt.Println(string(value3))
    

    Obviously it is not sensible to ignore the errors, but for the purpose of brevity I do it here.

    https://play.golang.org/p/fRQUfmZQke

    Results:

    test1
    test2
    test3
    

    From here, it is straight forward to fit back into your existing code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)