douxuelv7755 2016-02-21 04:42
浏览 32
已采纳

将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 2016-02-21 05:24
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置