/
histogram_read.go
58 lines (54 loc) · 1.8 KB
/
histogram_read.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package histogram
import (
"fmt"
"strconv"
"strings"
"github.com/grokify/gocharts/v2/data/table"
"github.com/grokify/mogo/type/stringsutil"
)
// ParseFileCSV reads a CSV using default settings of
// `,` separator, header row and BOM to be stripped. If you
// have other configurations, use `table.ReadFile()` directly
// and call `HistogramFromTable()`.
func ParseFileCSV(file string, name string, binNameColIdx, binFrequencyColIdx uint) (*Histogram, error) {
tbl, err := table.ReadFile(nil, file)
if err != nil {
return nil, err
}
tbl.Name = name
return ParseTable(tbl, binNameColIdx, binFrequencyColIdx)
}
// ParseTable parses a `table.Table` to a `Histogram` given a table,
// binName column index and binFrequency column index. Empty rows are
// skipped.
func ParseTable(tbl table.Table, binNameColIdx, binFrequencyColIdx uint) (*Histogram, error) {
hist := NewHistogram(tbl.Name)
for _, row := range tbl.Rows {
if stringsutil.SliceIsEmpty(row, true) {
continue
}
if int(binNameColIdx) >= len(row) {
return hist, fmt.Errorf("error row length smaller than binNameColIdx: recordLen[%d] binNameColIdx [%d]",
len(row), binNameColIdx)
} else if int(binFrequencyColIdx) >= len(row) {
return hist, fmt.Errorf("error row length smaller than binFrequencyColIdx: recordLen[%d] binFrequencyColIdx [%d]",
len(row), binFrequencyColIdx)
}
binName := strings.TrimSpace(row[binNameColIdx])
binFreq := strings.TrimSpace(row[binFrequencyColIdx])
if len(binName) == 0 && len(binFreq) == 0 {
continue
}
if len(binFreq) == 0 {
hist.Add(binName, 0)
} else {
binFreqInt, err := strconv.Atoi(binFreq)
if err != nil {
return hist, fmt.Errorf("error strconv frequency string[%s] err[%s]", binFreq, err.Error())
}
hist.Add(binName, binFreqInt)
}
}
hist.Inflate()
return hist, nil
}