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"])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)