-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcsvparser.go
66 lines (52 loc) · 1.03 KB
/
csvparser.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
59
60
61
62
63
64
65
66
// Copyright 2015 geOps
// Authors: [email protected]
//
// Use of this source code is governed by a GPL v2
// license that can be found in the LICENSE file
package gtfsparser
import (
"encoding/csv"
"io"
)
type CsvParser struct {
header []string
reader *csv.Reader
Curline int
}
func NewCsvParser(file io.Reader) CsvParser {
reader := csv.NewReader(file)
reader.TrimLeadingSpace = true
reader.LazyQuotes = true
reader.FieldsPerRecord = -1
p := CsvParser{reader: reader}
p.ParseHeader()
return p
}
func (p *CsvParser) ParseRecord() map[string]string {
l := p.ParseCsvLine()
if l == nil {
return nil
}
record := make(map[string]string)
for i, e := range p.header {
if i >= len(l) {
record[e] = ""
} else {
record[e] = l[i]
}
}
return record
}
func (p *CsvParser) ParseCsvLine() []string {
record, err := p.reader.Read()
p.Curline++
if err == io.EOF {
return nil
} else if err != nil {
panic(err.Error())
}
return record
}
func (p *CsvParser) ParseHeader() {
p.header = p.ParseCsvLine()
}