donglan9517 2019-05-22 12:48
浏览 7
已采纳

逐行读取特定数据

I am trying to read data from a file in specific format.

file looks as follows

title:stack|content:overflow|metadata:53|comments:none
title:google|content:website|metadata:213|comments:Demos

I need to read this line by line and assign title variable with title value ("stack"), content with content value ("overflow") for each line.

scanner := bufio.NewScanner(file)
        for scanner.Scan() {
                data := scanner.Text()
                data_arr := strings.Split(data, "|")

                for _, n := range data_arr {

                        data_subdoc := strings.Split(n, ":")
                        a, b := data_subdoc[0], data_subdoc[1]

                        fmt.Println(a, b)

But problem is I get data as (relation between title, content, metadata and comments for each line is missing)

title stack
content overflow
metadata 53
comments none
title google
content website
metadata 213 
comments Demos

But, I want something like:

stack overflow 53

if stack has 53:
    print comments (in this case, its 'none')

google website 213

if google has 213, print content (In this case, its 'website')
  • 写回答

1条回答 默认 最新

  • dongyingtang3803 2019-05-22 16:01
    关注

    As @LutzHorn suggested, why not read your data into a struct? The code below does that using reflection (though without checking for existence or type of field).

    package main
    
    import (
        "bufio"
        "fmt"
        "reflect"
        "strings"
    )
    
    type Entry struct {
        Title    string
        Content  string
        Metadata string
        Comments string
    }
    
    func main() {
        var input string = `title:stack|content:overflow|metadata:53|comments:none
    title:google|content:website|metadata:213|comments:Demos
    `
    
        var result = make(map[string]Entry)
    
        scanner := bufio.NewScanner(strings.NewReader(input))
        for scanner.Scan() {
            data := scanner.Text()
            data_arr := strings.Split(data, "|")
    
            entry := Entry{}
    
            for _, n := range data_arr {
    
                data_subdoc := strings.Split(n, ":")
                key, value := data_subdoc[0], data_subdoc[1]
    
                fmt.Println(key, value)
    
                field := strings.Title(key)
                reflect.Indirect(reflect.ValueOf(&entry)).FieldByName(field).SetString(value)
            }
    
            result[entry.Metadata] = entry
        }
    
        fmt.Printf("%+v
    ", result["53"])
        fmt.Printf("%+v
    ", result["213"])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题