This commit is contained in:
Alex Yatskov 2024-03-30 21:47:56 -07:00
parent e2d85e441e
commit 73aca287d3

52
main.go
View File

@ -2,6 +2,7 @@ package main
import (
"encoding/csv"
"encoding/json"
"errors"
"flag"
"fmt"
@ -35,11 +36,40 @@ type (
Table = []TableRow
)
func injectStories(table Table, path string) error {
func injectStories(table Table, path string, heisigIndex int) error {
fp, err := os.Open(path)
if err != nil {
return err
}
defer fp.Close()
decoder := json.NewDecoder(fp)
var characters []KanjiEntry
if err := decoder.Decode(&characters); err != nil {
return err
}
for i, row := range table {
for _, character := range characters {
if character.Character != row[heisigIndex] {
continue
}
var stories strings.Builder
for _, story := range character.Stories {
stories.WriteString(fmt.Sprintf("<span>%s</span>", story.Content))
}
row = append(row, stories.String())
table[i] = row
}
}
return nil
}
func injectKanjidic(table Table, path string) error {
func injectKanjidic(table Table, path string, heisigIndex int) error {
fp, err := os.Open(path)
if err != nil {
return err
@ -54,7 +84,7 @@ func injectKanjidic(table Table, path string) error {
for i, row := range table {
var found bool
for _, character := range kd.Characters {
if character.Literal != row[0] {
if character.Literal != row[heisigIndex] {
continue
}
@ -96,7 +126,7 @@ func injectKanjidic(table Table, path string) error {
return nil
}
func loadTable(path string) (Table, error) {
func loadTable(path string, heisigIndex, columnLimit int) (Table, error) {
fp, err := os.Open(path)
if err != nil {
return nil, err
@ -113,9 +143,9 @@ func loadTable(path string) (Table, error) {
}
for i := range table {
table[i] = table[i][:3]
if len(table[i]) != 3 {
return nil, errors.New("unexpected column count")
table[i] = table[i][:columnLimit]
if len(table[i]) < heisigIndex {
return nil, errors.New("unexpected heisig index")
}
}
@ -141,6 +171,8 @@ func main() {
var (
storiesPath = flag.String("stories", "", "path for stories JSON")
kanjidicPath = flag.String("kanjidic", "", "path for KANJIDIC")
heisigIndex = flag.Int("heisig", 0, "heisig index column index")
columnLimit = flag.Int("columns", 3, "column trim value")
)
flag.Usage = func() {
@ -157,19 +189,19 @@ func main() {
os.Exit(2)
}
table, err := loadTable(args[0])
table, err := loadTable(args[0], *heisigIndex, *columnLimit)
if err != nil {
log.Fatal(err)
}
if len(*storiesPath) > 0 {
if err := injectStories(table, *storiesPath); err != nil {
if err := injectStories(table, *storiesPath, *heisigIndex); err != nil {
log.Fatal(err)
}
}
if len(*kanjidicPath) > 0 {
if err := injectKanjidic(table, *kanjidicPath); err != nil {
if err := injectKanjidic(table, *kanjidicPath, *heisigIndex); err != nil {
log.Fatal(err)
}
}