douxuelv7755
douxuelv7755
2016-02-21 04:42

将CSV字符串读入自定义对象列表Go语言

已采纳

I am trying to read a string of data from a csv file and parse the data into a list of custom objects. The main issue that I am having is converting the data to the correct datatype within the loop.

Here is my custom object:

type yahooInfoObj struct {
    date time.Time
    open float32
    high float32
    low float32
    close float32
    volume int
    adjClose float32
}

Here is my function that gets the data and attempts to parse it:

func getSingleCompanyData(search searchObj) []yahooInfoObj {
    searchQuery := buildYahooFinanceDataQueryString(search)
    data := getRequest(searchQuery)

    r := csv.NewReader(strings.NewReader(data))
    var stats []yahooInfoObj

    // Read csv file
    result, _ := r.ReadAll()

    //loop through each returned stat (line)
    for i := range result {
        //skip the first entry due to column names being returned
        if i != 0{
            stat := result[i]
            stats = append(stats, yahooInfoObj{stat[0],strconv.ParseFloat(stat[1],32),strconv.ParseFloat(stat[2],32),strconv.ParseFloat(stat[3],32),strconv.ParseFloat(stat[4],32),strconv.Atoi(stat[5]),strconv.ParseFloat(stat[6],32)})
        }
    }

    return stats
}

Here is some sample data of which would be returned and placed in the data variable:

Date,Open,High,Low,Close,Volume,Adj Close
2010-12-31,31.219999,31.33,30.93,31.299999,11716300,29.517661
2010-12-30,31.450001,31.58,31.209999,31.290001,12989400,29.508232
2010-12-29,31.530001,31.690001,31.42,31.50,9769000,29.706273
2010-12-28,31.66,31.76,31.41,31.57,9736000,29.772287

I am new to the go language and would really appreciate any advice. Thanks in advance!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanjiaolia97750 duanjiaolia97750 5年前

    There's a few things that I notice right off the bat:

    • You're not using a time.Time object to send to your yahooInfoObj struct. You're sending a string

    • You're calling functions that return multiple values in a "single value context". This means that you are just expecting to ignore the second value, but to Go this is an error in your coding. You'll have to explicitly set these values.

    • You're not checking multiple errors. Always check errors - it'll prevent "gotchas" in the future.

    It's not perfect, but here's a seemingly working playground: https://play.golang.org/p/idQFFVjS-X

    点赞 评论 复制链接分享