Last active
February 19, 2024 21:19
-
-
Save wenjie1991/7d8db205760a08940f5147938d45c43b to your computer and use it in GitHub Desktop.
Transform kindle clippings to markdowns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env raku | |
use v6.d; | |
##################################### | |
## Process kindle clippings file | |
## Author: Wenjie SUN | |
## Date: 2024-2-19 | |
## Email: sunwjie at gmail.com | |
## Input: My Clippings - Kindle.txt | |
## Output: A folder named "kindle-notes" with each note saved as a markdown file. | |
##################################### | |
# Reads the entire content of the file into a string. The `.IO.slurp` method reads files efficiently. | |
my @note = "./My Clippings - Kindle.txt".IO.slurp.split: "\n==========\n"; | |
# Declares a hash (associative array) to store notes. The key is the title of the note, and the value is the note content. | |
my %note; | |
my @title-vec = <Any>.Array; | |
# Iterates over each note in the @note array. The `map` function is used here for its side effects, | |
# not for transforming the array. For each note, it splits the note into lines: | |
# - The first line is treated as the title. | |
# - The second line is treated as the location. | |
# - The third line is an empty line used as a separator. | |
# - The fourth and subsequent lines contain the actual note content. | |
# Then, if the note content is defined (i.e., not empty), it pushes the note content into the array associated with the title in %note. | |
for @note -> $note-elem { | |
my ($title, $note) = $note-elem.split("\n", 4)[0, 3]; | |
%note{$title}.push: $note with $note; | |
} | |
## crerate a folder for all the notes | |
my $folder = "kindle-notes"; | |
mkdir $folder unless $folder.IO.e; | |
# This commented-out line filtering titles based on a regex pattern and then joining them with a newline. | |
# It's filtering titles that do not start with certain characters but it's commented out, so it has no effect on the script's execution. | |
# say %note.keys.map({$_ ~~ m/^<-[\(\(]>+/}).join("\n"); | |
# Iterates over each key-value pair in the %note hash. `%note.kv` provides a list of title-note pairs. | |
# For each pair, it prints the title prefixed with a "# " to indicate the title. | |
# Then, for each note associated with that title, it prints the note content, prefixed with "- ". | |
# Only prints the note if it's not an empty string. | |
## save each note to a file | |
for %note.kv -> $title, @note { | |
my $file = "$folder/{$title.subst(/\s+$/, "")}.md"; | |
my $fh = open $file, :w; | |
$fh.say: "# " ~ ($title ~~ m/^<-[\(\(]>+/); | |
for @note { $fh.say: '- ' ~ $_ with $_ }; | |
$fh.close; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment