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

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

使用 csv 讀取處理單值上下文中的多值

使用 csv 讀取處理單值上下文中的多值

Go
慕田峪7331174 2022-06-06 17:48:06
試圖從 csv 文件中讀取date和讀取number,所以我有以下結構type Transaction struct {    Warehouse string    `json:"warehouse"`    Item      string    `json:"item"`    Movement  string    `json:"movement"`    Batch     string    `json:"batch"`    Date      time.Time `json:"transaction_data"`    Quantity  uint64    `json:"quantity"`}type Transactions struct {    header []string    lines  []Transaction}并進行如下閱讀:func main() {    // Reading csv file thread > START //    pairs := []Pair{{"m", 1}, {"d", 0}, {"c", 2}}    fmt.Println(pairs)    // Sort by Key    sort.Sort(ByKey(pairs))    fmt.Println(pairs)    pairs = append(pairs, Pair{"h", 5})    fmt.Println(pairs)    // Reading csv file thread > START //    input := make(chan Transactions)    go func(input_file string) {        var trx Transactions        fr, err := os.Open(input_file)        failOnError(err)        defer fr.Close()        r := csv.NewReader(fr)        rows, err := r.ReadAll()        failOnError(err)        trx.header = rows[0]        for _, row := range rows[1:] {            trx.lines = append(trx.lines, Transaction{                Warehouse: strings.TrimSpace(row[0]),                Item:      strings.TrimSpace(row[1]),                Movement:  strings.TrimSpace(row[2]),                Batch:     strings.TrimSpace(row[3]),                Date:      time.Parse("%Y-%m-%d", row[4]),                   // multiple-value in single-value context error                Quantity:  (strconv.ParseFloat(row[5], 64) * 1000).(uint64),  // multiple-value in single-value context error            })        }        peopleJson, _ := json.Marshal(trx.lines)        fmt.Println(string(peopleJson))         input <- trx // send data to channel read    }("trx.csv")    <-input // rceive from channel 'read' and assign value to new data variable    // Reading csv file thread < END //}
查看完整描述

1 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

我得到了答案(感謝富有成效的評論,只有富有成效的評論)


解決方案制作一個單獨的函數來讀取 2 上下文,并僅返回如下值:


func mustTime(t time.Time, err error) time.Time { failOnError(err); return t }

func mustNumber(d float64, err error) uint64    { failOnError(err); return uint64(d + 1000) }

然后將其稱為:


Date:      mustTime(time.Parse("%Y-%m-%d", row[4])),

Quantity:  mustNumber(strconv.ParseFloat(row[5], 64)),

因此,完整正確的代碼變為:


package main


import (

    "encoding/csv"

    "encoding/json"

    "fmt"

    "log"

    "os"

    "sort"

    "strconv"

    "strings"

    "time"

)


func failOnError(err error) {

    if err != nil {

        log.Fatal("Error:", err)

        panic(err)

    }

}


type Pair struct {

    Key   string

    Value float64

}


type ByKey []Pair


func (s ByKey) Len() int {

    return len(s)

}


func (s ByKey) Swap(i, j int) {

    s[i], s[j] = s[j], s[i]

}


func (s ByKey) Less(i, j int) bool {

    return s[i].Key < s[j].Key

}


func (s ByKey) pop() bool {

    //s = append(s,[0 : s.Len()-1])

    return true

}


func main() {

    // Reading csv file thread > START //

    pairs := []Pair{{"m", 1}, {"d", 0}, {"c", 2}}

    fmt.Println(pairs)

    // Sort by Key

    sort.Sort(ByKey(pairs))

    fmt.Println(pairs)

    pairs = append(pairs, Pair{"h", 5})

    fmt.Println(pairs)


    // Reading csv file thread > START //

    input := make(chan Transactions)

    go func(input_file string) {

        var trx Transactions

        fr, err := os.Open(input_file)

        failOnError(err)

        defer fr.Close()

        r := csv.NewReader(fr)

        rows, err := r.ReadAll()

        failOnError(err)

        trx.header = rows[0]

        for _, row := range rows[1:] {

            trx.lines = append(trx.lines, Transaction{

                Warehouse: strings.TrimSpace(row[0]),

                Item:      strings.TrimSpace(row[1]),

                Movement:  strings.TrimSpace(row[2]),

                Batch:     strings.TrimSpace(row[3]),

                Date:      mustTime(time.Parse("%Y-%m-%d", row[4])),

                Quantity:  mustNumber(strconv.ParseFloat(row[5], 64)),

            })

        }


        peopleJson, _ := json.Marshal(trx.lines)

        fmt.Println(string(peopleJson)) // This is working smoothly


        input <- trx // send data to channel read

    }("trx.csv")

    //data :=

    <-input // rceive from channel 'read' and assign value to new data variable

    // Reading csv file thread < END //

}


type Transactions struct {

    header []string

    lines  []Transaction

}


type Transaction struct {

    Warehouse string    `json:"warehouse"`

    Item      string    `json:"item"`

    Movement  string    `json:"movement"`

    Batch     string    `json:"batch"`

    Date      time.Time `json:"transaction_data"`

    Quantity  uint64    `json:"quantity"`

}


func mustTime(t time.Time, err error) time.Time { failOnError(err); return t }

func mustNumber(d float64, err error) uint64    { failOnError(err); return uint64(d + 1000) }



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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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