Skip to content

Instantly share code, notes, and snippets.

@matheusoliveira
Last active July 6, 2022 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matheusoliveira/3adaa5f7a697c3749f850afbedd06d0f to your computer and use it in GitHub Desktop.
Save matheusoliveira/3adaa5f7a697c3749f850afbedd06d0f to your computer and use it in GitHub Desktop.
// Simple example to read CSV format from nomes.csv at https://brasil.io/dataset/genero-nomes/files/
package main
import (
"encoding/csv"
"fmt"
"os"
"strconv"
"strings"
)
type Name struct {
AlternativeNames []string
Classification string
FirstName string
FrequencyFemale int
FrequencyMale int
FrequencyTotal int
FrequencyGroup int
GroupName string
Ratio float32
}
func intOrZero(val string) int {
if ret, err := strconv.Atoi(val); err == nil {
return ret
} else {
return 0
}
}
func floatOrZero(val string) float32 {
if ret, err := strconv.ParseFloat(val, 32); err == nil {
return float32(ret)
} else {
return 0
}
}
func main() {
csvFile, err := os.Open("nomes.csv")
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened CSV file")
defer csvFile.Close()
csvLines, err := csv.NewReader(csvFile).ReadAll()
if err != nil {
fmt.Println(err)
}
for i, line := range csvLines {
if i == 0 {
// skip header
continue
}
name := Name{
AlternativeNames: strings.Split(line[0], "|"),
Classification: line[1],
FirstName: line[2],
FrequencyFemale: intOrZero(line[3]),
FrequencyMale: intOrZero(line[4]),
FrequencyTotal: intOrZero(line[5]),
FrequencyGroup: intOrZero(line[6]),
GroupName: line[7],
Ratio: floatOrZero(line[8]),
}
if name.FirstName == "DOMINIC" {
fmt.Printf("%+v\n", name)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment