使用 csv 读取处理单值上下文中的多值

试图从 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 //

}


慕田峪7331174
浏览 178回答 1
1回答

慕沐林林

我得到了答案(感谢富有成效的评论,只有富有成效的评论)解决方案制作一个单独的函数来读取 2 上下文,并仅返回如下值:func mustTime(t time.Time, err error) time.Time { failOnError(err); return t }func mustNumber(d float64, err error) uint64&nbsp; &nbsp; { failOnError(err); return uint64(d + 1000) }然后将其称为:Date:&nbsp; &nbsp; &nbsp; mustTime(time.Parse("%Y-%m-%d", row[4])),Quantity:&nbsp; mustNumber(strconv.ParseFloat(row[5], 64)),因此,完整正确的代码变为:package mainimport (&nbsp; &nbsp; "encoding/csv"&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "os"&nbsp; &nbsp; "sort"&nbsp; &nbsp; "strconv"&nbsp; &nbsp; "strings"&nbsp; &nbsp; "time")func failOnError(err error) {&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("Error:", err)&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }}type Pair struct {&nbsp; &nbsp; Key&nbsp; &nbsp;string&nbsp; &nbsp; Value float64}type ByKey []Pairfunc (s ByKey) Len() int {&nbsp; &nbsp; return len(s)}func (s ByKey) Swap(i, j int) {&nbsp; &nbsp; s[i], s[j] = s[j], s[i]}func (s ByKey) Less(i, j int) bool {&nbsp; &nbsp; return s[i].Key < s[j].Key}func (s ByKey) pop() bool {&nbsp; &nbsp; //s = append(s,[0 : s.Len()-1])&nbsp; &nbsp; return true}func main() {&nbsp; &nbsp; // Reading csv file thread > START //&nbsp; &nbsp; pairs := []Pair{{"m", 1}, {"d", 0}, {"c", 2}}&nbsp; &nbsp; fmt.Println(pairs)&nbsp; &nbsp; // Sort by Key&nbsp; &nbsp; sort.Sort(ByKey(pairs))&nbsp; &nbsp; fmt.Println(pairs)&nbsp; &nbsp; pairs = append(pairs, Pair{"h", 5})&nbsp; &nbsp; fmt.Println(pairs)&nbsp; &nbsp; // Reading csv file thread > START //&nbsp; &nbsp; input := make(chan Transactions)&nbsp; &nbsp; go func(input_file string) {&nbsp; &nbsp; &nbsp; &nbsp; var trx Transactions&nbsp; &nbsp; &nbsp; &nbsp; fr, err := os.Open(input_file)&nbsp; &nbsp; &nbsp; &nbsp; failOnError(err)&nbsp; &nbsp; &nbsp; &nbsp; defer fr.Close()&nbsp; &nbsp; &nbsp; &nbsp; r := csv.NewReader(fr)&nbsp; &nbsp; &nbsp; &nbsp; rows, err := r.ReadAll()&nbsp; &nbsp; &nbsp; &nbsp; failOnError(err)&nbsp; &nbsp; &nbsp; &nbsp; trx.header = rows[0]&nbsp; &nbsp; &nbsp; &nbsp; for _, row := range rows[1:] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; trx.lines = append(trx.lines, Transaction{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Warehouse: strings.TrimSpace(row[0]),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Item:&nbsp; &nbsp; &nbsp; strings.TrimSpace(row[1]),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Movement:&nbsp; strings.TrimSpace(row[2]),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Batch:&nbsp; &nbsp; &nbsp;strings.TrimSpace(row[3]),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Date:&nbsp; &nbsp; &nbsp; mustTime(time.Parse("%Y-%m-%d", row[4])),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Quantity:&nbsp; mustNumber(strconv.ParseFloat(row[5], 64)),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; peopleJson, _ := json.Marshal(trx.lines)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(string(peopleJson)) // This is working smoothly&nbsp; &nbsp; &nbsp; &nbsp; input <- trx // send data to channel read&nbsp; &nbsp; }("trx.csv")&nbsp; &nbsp; //data :=&nbsp; &nbsp; <-input // rceive from channel 'read' and assign value to new data variable&nbsp; &nbsp; // Reading csv file thread < END //}type Transactions struct {&nbsp; &nbsp; header []string&nbsp; &nbsp; lines&nbsp; []Transaction}type Transaction struct {&nbsp; &nbsp; Warehouse string&nbsp; &nbsp; `json:"warehouse"`&nbsp; &nbsp; Item&nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; `json:"item"`&nbsp; &nbsp; Movement&nbsp; string&nbsp; &nbsp; `json:"movement"`&nbsp; &nbsp; Batch&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; `json:"batch"`&nbsp; &nbsp; Date&nbsp; &nbsp; &nbsp; time.Time `json:"transaction_data"`&nbsp; &nbsp; Quantity&nbsp; uint64&nbsp; &nbsp; `json:"quantity"`}func mustTime(t time.Time, err error) time.Time { failOnError(err); return t }func mustNumber(d float64, err error) uint64&nbsp; &nbsp; { failOnError(err); return uint64(d + 1000) }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go