Skip to content

Instantly share code, notes, and snippets.

@cblgh

cblgh/md-to-anki.go

Last active Jun 4, 2021
Embed
What would you like to do?
convert a file containing prompts with markdown to a tsv file with cards containing html (easy to import via anki)
package main
import (
"github.com/gomarkdown/markdown"
"strings"
"path/filepath"
"time"
"fmt"
"io"
"os"
"log"
)
func check (err error) {
if err != nil {
log.Fatalln(err)
}
}
func markup (s string) string {
return strings.ReplaceAll(string(markdown.ToHTML([]byte(s), nil, nil)), "\n", "<br>")
}
func main () {
if len(os.Args) < 2 {
fmt.Println("usage: prompts <path/to/prompts.md>\noutputs <path/to/prompts-yyyy-mm-dd-hhmm.tsv>")
os.Exit(0)
}
filename := os.Args[1]
file, err := os.Open(filename)
check(err)
contents, err := io.ReadAll(file)
check(err)
// create cards using blanklines as delimiters; handle windows delimiters
cards := strings.Split(strings.ReplaceAll(string(contents), "\r\n", "\n"), "\n\n")
// if file started with a title, remove that "card"
if strings.HasPrefix(cards[0], "#") { cards = cards[1:] }
processed := make([]string, 0, len(cards))
for _, card := range cards {
// get the front & back fields of the card by using \n as the field delimiter
fields := strings.Split(strings.TrimSpace(card), "\n")
fmt.Printf("%q\n", fields)
// treat first field as special (question), remaining fields should be collapsed into the same string
question := markup(fields[0])
answer := markup(strings.Join(fields[1:], "\n"))
processed = append(processed, strings.Join([]string{question, answer}, "\t"))
}
// output the processed prompt data to a file we can import in anki
date := time.Now().Format("2006-01-02")
outpath := filepath.Join(filepath.Dir(filename), fmt.Sprintf("prompts-%s.tsv", date))
fmt.Println(outpath)
err = os.WriteFile(outpath, []byte(strings.Join(processed, "\n")), 0644)
check(err)
}
@cblgh

This comment has been minimized.

Copy link
Owner Author

@cblgh cblgh commented Jun 4, 2021

example card formatting:

In golang, what package do you use to create files?
`os`

In golang, what is the signature for creating a file?
`os.Create(string, []byte, uint) error`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment