本文整理匯總了Golang中encoding/csv.Reader.Read方法的典型用法代碼示例。如果您正苦於以下問題:Golang Reader.Read方法的具體用法?Golang Reader.Read怎麽用?Golang Reader.Read使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類encoding/csv.Reader
的用法示例。
在下文中一共展示了Reader.Read方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: LoadCases
//LoadCases will load data stored case by case from a cvs reader into a
//feature matrix that has allready been filled with the coresponding empty
//features. It is a lower level method generally called after inital setup to parse
//a fm, arff, csv etc.
func (fm *FeatureMatrix) LoadCases(data *csv.Reader, rowlabels bool) {
count := 0
for {
record, err := data.Read()
if err == io.EOF {
break
} else if err != nil {
log.Print("Error:", err)
break
}
caselabel := fmt.Sprintf("%v", count)
if rowlabels {
caselabel = record[0]
record = record[1:]
}
fm.CaseLabels = append(fm.CaseLabels, caselabel)
for i, v := range record {
fm.Data[i].Append(v)
}
count++
}
}
示例2: Read
// Read takes a CSV reader and reads it into a typed List of structs. Each row gets read into a struct named structName, described by headers. If the original data contained headers it is expected that the input reader has already read those and are pointing at the first data row.
// If kinds is non-empty, it will be used to type the fields in the generated structs; otherwise, they will be left as string-fields.
// In addition to the list, Read returns the typeRef for the structs in the list, and last the typeDef of the structs.
func Read(r *csv.Reader, structName string, headers []string, kinds KindSlice, vrw types.ValueReadWriter) (l types.List, typeRef, typeDef types.Type) {
typeRef, typeDef = MakeStructTypeFromHeaders(headers, structName, kinds)
valueChan := make(chan types.Value, 128) // TODO: Make this a function param?
listType := types.MakeCompoundType(types.ListKind, typeRef)
listChan := types.NewStreamingTypedList(listType, vrw, valueChan)
structFields := typeDef.Desc.(types.StructDesc).Fields
for {
row, err := r.Read()
if err == io.EOF {
close(valueChan)
break
} else if err != nil {
panic(err)
}
fields := make(map[string]types.Value)
for i, v := range row {
if i < len(headers) {
f := structFields[i]
fields[f.Name] = StringToType(v, f.T.Kind())
}
}
valueChan <- types.NewStruct(typeRef, typeDef, fields)
}
return <-listChan, typeRef, typeDef
}
示例3: streamCsv
// streamCsv
// Streams a CSV Reader into a returned channel. Each CSV row is streamed along with the header.
// "true" is sent to the `done` channel when the file is finished.
//
// Args
// csv - The csv.Reader that will be read from.
// buffer - The "lines" buffer factor. Send "0" for an unbuffered channel.
func streamCsv(csv *csv.Reader, buffer int) (lines chan *CsvLine) {
lines = make(chan *CsvLine, buffer)
go func() {
// get Header
header, err := csv.Read()
if err != nil {
close(lines)
return
}
i := 0
for {
line, err := csv.Read()
if len(line) > 0 {
i++
lines <- &CsvLine{Header: header, Line: line}
}
if err != nil {
fmt.Printf("Sent %d lines\n", i)
close(lines)
return
}
}
}()
return
}
示例4: unmarshalCensusData
// Reads the census CSV data from files
func unmarshalCensusData(reader *csv.Reader, v interface{}) error {
record, err := reader.Read()
if err != nil {
return err
}
s := reflect.ValueOf(v).Elem()
if s.NumField() != len(record) {
return &csvFieldMismatch{s.NumField(), len(record)}
}
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
switch f.Type().String() {
case "string":
f.SetString(record[i])
case "int":
ival, err := strconv.ParseInt(record[i], 10, 0)
if err != nil {
return err
}
f.SetInt(ival)
case "float64":
fval, err := strconv.ParseFloat(record[i], 64)
if err != nil {
return err
}
f.SetFloat(fval)
default:
return &csvUnsupportedType{f.Type().String()}
}
}
return nil
}
示例5: parseColumns
// Parse columns from first header row or from flags
func parseColumns(reader *csv.Reader, skipHeader bool, fields string) ([]string, error) {
var err error
var columns []string
if fields != "" {
columns = strings.Split(fields, ",")
if skipHeader {
reader.Read() //Force consume one row
}
} else {
columns, err = reader.Read()
if err != nil {
return nil, err
}
}
for _, col := range columns {
if containsDelimiter(col) {
return columns, errors.New("Please specify the correct delimiter with -d.\nHeader column contains a delimiter character: " + col)
}
}
for i, col := range columns {
columns[i] = postgresify(col)
}
return columns, nil
}
示例6: NewUserFromCSV
// User CSV
// Fields are stored in the sequence as they appear in the struct, with arrays
// being represented as semicolon separated lists.
// Create a new user read from a CSV reader
func NewUserFromCSV(reader *csv.Reader) (user *User, done bool) {
line, err := reader.Read()
if err != nil {
return nil, true
}
if len(line) != 7 {
return nil, false
}
// comment
firstElement := strings.TrimSpace(line[0])
if len(firstElement) > 0 && firstElement[0] == '#' {
return nil, false
}
level := line[2]
ValidFrom, _ := time.Parse("2006-01-02 15:04", line[4])
ValidTo, _ := time.Parse("2006-01-02 15:04", line[5])
if !isValidLevel(level) {
log.Printf("Got invalid level '%s'", level)
return nil, false
}
return &User{
Name: line[0],
ContactInfo: line[1],
UserLevel: Level(level),
Sponsors: strings.Split(line[3], ";"),
ValidFrom: ValidFrom, // field 4
ValidTo: ValidTo, // field 5
Codes: strings.Split(line[6], ";")},
false
}
示例7: ReadToList
// Read takes a CSV reader and reads it into a typed List of structs. Each row gets read into a struct named structName, described by headers. If the original data contained headers it is expected that the input reader has already read those and are pointing at the first data row.
// If kinds is non-empty, it will be used to type the fields in the generated structs; otherwise, they will be left as string-fields.
// In addition to the list, Read returns the typeRef for the structs in the list, and last the typeDef of the structs.
func ReadToList(r *csv.Reader, structName string, headers []string, kinds KindSlice, vrw types.ValueReadWriter) (l types.List, t *types.Type) {
t, fieldOrder, kindMap := MakeStructTypeFromHeaders(headers, structName, kinds)
valueChan := make(chan types.Value, 128) // TODO: Make this a function param?
listChan := types.NewStreamingList(vrw, valueChan)
for {
row, err := r.Read()
if err == io.EOF {
close(valueChan)
break
} else if err != nil {
panic(err)
}
fields := make(types.ValueSlice, len(headers))
for i, v := range row {
if i < len(headers) {
fieldOrigIndex := fieldOrder[i]
val, err := StringToValue(v, kindMap[fieldOrigIndex])
if err != nil {
d.Chk.Fail(fmt.Sprintf("Error parsing value for column '%s': %s", headers[i], err))
}
fields[fieldOrigIndex] = val
}
}
valueChan <- types.NewStructWithType(t, fields)
}
return <-listChan, t
}
示例8: read_record
func read_record(csv_reader *csv.Reader) (loadedRecord, error) {
row, err := csv_reader.Read()
if err != nil {
return loadedRecord{}, err
}
if err != nil {
panic(err)
}
var id, key string
if len(row) == 2 {
id, key = row[0], row[1]
} else {
key = row[0]
}
numeric, _ := regexp.Compile("[0-9]")
new_key := numeric.ReplaceAllString(key, "")
new_key = strings.ToLower(new_key)
record := loadedRecord{
id: id,
key: new_key,
original_key: key,
length: len(new_key) - 2,
}
record.trigrams = create_trigram(new_key, record.length)
return record, nil
}
示例9: readCsv
func readCsv(ch chan []string) {
var reader *csv.Reader
if inputFn == "" {
reader = csv.NewReader(os.Stdin)
} else {
file, err := os.Open(inputFn)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
defer file.Close()
reader = csv.NewReader(file)
}
if !strictLen {
reader.FieldsPerRecord = -1
}
r, _ := utf8.DecodeRuneInString(inputSep)
reader.Comma = r
reader.LazyQuotes = lazyQuotes
for {
record, err := reader.Read()
if err == io.EOF {
close(ch)
break
} else if err != nil {
fmt.Println("Error:", err)
close(ch)
break
}
ch <- record
}
}
示例10: start
func (t *table) start(reader *csv.Reader) {
defer t.Stop()
defer close(t.rows)
headers, err := reader.Read()
if err != nil {
if perr, ok := err.(*csv.ParseError); ok {
// Modifies the underlying err
perr.Err = fmt.Errorf("%s. %s", perr.Err, "This can happen when the CSV is malformed, or when the wrong delimiter is used")
}
t.handleErr(err)
return
}
reader.FieldsPerRecord = len(headers)
for {
if t.stopped {
break
}
line, err := reader.Read()
if err != nil {
t.handleErr(err)
return
}
t.rows <- convertLineToRow(line, headers)
}
}
示例11: processFile
func processFile(reader *csv.Reader, keyIndex, valueIndex int, headerRow bool) ([]MapEntry, error) {
entries := []MapEntry{}
for i := 0; true; i++ {
row, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if headerRow && i == 0 {
continue
}
numFields := len(row)
if keyIndex > numFields {
return nil, fmt.Errorf("key index '%d' > number of fields '%d'", keyIndex, numFields)
}
if valueIndex > numFields {
return nil, fmt.Errorf("value index '%d' > number of fields '%d'", valueIndex, numFields)
}
key := row[keyIndex-1]
value := row[valueIndex-1]
entries = append(entries, MapEntry{key, value})
}
return entries, nil
}
示例12: RecsFromCSVReader
func RecsFromCSVReader(r *csv.Reader, recs map[string][]RepoRelation) error {
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to read csv record: %v", err)
}
if len(record[0]) < prefixLen {
log.Printf("not valid rec record %v", record)
continue
}
sp1 := ShortPathFromURL(record[0])
sp2 := ShortPathFromURL(record[1])
c, err := strconv.ParseFloat(record[2], 64)
if err != nil {
log.Printf("Failed to ParseFloat(%q, 64): %v", record[2], err)
}
recs[sp1] = append(recs[sp1], RepoRelation{sp2, c})
}
for k, _ := range recs {
sort.Sort(ByScore(recs[k]))
}
log.Printf("%v recs has been loaded", len(recs))
return nil
}
示例13: readFeatures
func (d *Data) readFeatures(in csv.Reader) {
for {
record, err := in.Read()
if err == io.EOF {
break
}
if err != nil {
fmt.Println("ERROR: ", err)
}
x := len(record)
conv := make([]float64, x, x)
correctData := true
for i := 0; i < x; i++ {
conv[i], err = strconv.ParseFloat(record[i], 64)
if err != nil {
fmt.Println("ERROR: ", err)
correctData = false
}
}
if correctData {
d.AppendRow(conv)
}
}
}
示例14: readHeader
func (d *Data) readHeader(r csv.Reader) {
record, err := r.Read()
if err != nil {
fmt.Println("ERROR: ", err)
}
d.setFeatures(record)
}
示例15: readOneRecordAtaTime
func readOneRecordAtaTime(reader *csv.Reader) {
for {
row, err := reader.Read()
if err != nil {
break
}
printRow(row)
}
}