逐行读取特定数据

时间:2019-05-22 12:48:37

标签: regex go

我正在尝试从特定格式的文件中读取数据。

文件外观如下

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

我需要逐行阅读 为每一行分配标题变量,其值为title"stack"),内容为content"overflow")。

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)

但是问题是我得到的数据是(缺少每一行的标题,内容,元数据和注释之间的关系)

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

但是,我想要类似的东西:

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 个答案:

答案 0 :(得分:0)

正如@LutzHorn所建议的那样,为什么不将数据读入结构中呢?下面的代码使用反射来做到这一点(尽管不检查字段的存在或类型)。

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\n", result["53"])
    fmt.Printf("%+v\n", result["213"])
}