亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

逐行讀取特定數據

逐行讀取特定數據

Go
肥皂起泡泡 2023-06-19 15:52:16
我正在嘗試從特定格式的文件中讀取數據。文件如下所示title:stack|content:overflow|metadata:53|comments:nonetitle: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 stackcontent overflowmetadata 53comments nonetitle googlecontent websitemetadata 213 comments Demos但是,我想要這樣的東西:stack overflow 53if stack has 53:    print comments (in this case, its 'none')google website 213if google has 213, print content (In this case, its 'website')
查看完整描述

1 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

為什么不將數據讀入結構?下面的代碼使用反射來做到這一點(盡管沒有檢查字段的存在或類型)。


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"])

}


查看完整回答
反對 回復 2023-06-19
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號