读取 CSV 字符串并将其转换为自定义对象列表 Go 语言

huangapple go评论90阅读模式
英文:

Read CSV String Into List of Custom Objects Go Language

问题

我正在尝试从CSV文件中读取一串数据,并将数据解析为自定义对象的列表。我遇到的主要问题是在循环中将数据转换为正确的数据类型。

这是我的自定义对象:

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

这是我的获取数据并尝试解析的函数:

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

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

    // 读取CSV文件
    result, _ := r.ReadAll()

    // 遍历每个返回的统计数据(行)
    for i := range result {
        // 跳过第一个条目,因为返回的是列名
        if i != 0 {
            stat := result[i]
            date, _ := time.Parse("2006-01-02", stat[0])
            open, _ := strconv.ParseFloat(stat[1], 32)
            high, _ := strconv.ParseFloat(stat[2], 32)
            low, _ := strconv.ParseFloat(stat[3], 32)
            close, _ := strconv.ParseFloat(stat[4], 32)
            volume, _ := strconv.Atoi(stat[5])
            adjClose, _ := strconv.ParseFloat(stat[6], 32)

            stats = append(stats, yahooInfoObj{
                date:     date,
                open:     float32(open),
                high:     float32(high),
                low:      float32(low),
                close:    float32(close),
                volume:   volume,
                adjClose: float32(adjClose),
            })
        }
    }

    return stats
}

这是一些示例数据,将返回并放入data变量中:

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

我是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

得分: 1

我立即注意到几个问题:

  • 你没有使用time.Time对象发送给yahooInfoObj结构体,而是发送了一个字符串。

  • 你在“单值上下文”中调用返回多个值的函数。这意味着你只是希望忽略第二个值,但对于Go语言来说,这是你的代码中的错误。你需要显式地设置这些值。

  • 你没有检查多个错误。始终检查错误-这将防止将来出现“意外情况”。

这个示例可能不完美,但似乎可以工作:https://play.golang.org/p/idQFFVjS-X

英文:

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

huangapple
  • 本文由 发表于 2016年2月21日 12:42:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/35532414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定