summaryrefslogtreecommitdiffstats
path: root/kanji_info_fetcher/io.py
diff options
context:
space:
mode:
Diffstat (limited to 'kanji_info_fetcher/io.py')
-rw-r--r--kanji_info_fetcher/io.py50
1 files changed, 50 insertions, 0 deletions
diff --git a/kanji_info_fetcher/io.py b/kanji_info_fetcher/io.py
new file mode 100644
index 0000000..90c9507
--- /dev/null
+++ b/kanji_info_fetcher/io.py
@@ -0,0 +1,50 @@
+from os import path
+from dataclasses import dataclass
+
+@dataclass
+class Entry:
+ kanji: str
+ hiragana: str
+ english: str
+ meanings: str
+
+def read_from_file(path_str: str, row_format: str) -> list:
+ p = path.join(path_str)
+ lines = []
+
+ format_segments = row_format.split(",")
+
+ with open(p, "r") as f:
+ lines = f.readlines()
+
+ entries = []
+ for line in lines:
+ if len(line.strip()) == 0:
+ continue
+
+ value_dict = {}
+
+ row_values = line.split(",", len(format_segments) - 1)
+ for i, format_segment in enumerate(format_segments):
+ value_dict[format_segment] = row_values[i]
+
+ entries.append(Entry(
+ kanji=value_dict.get("kanji", "").strip(),
+ hiragana=value_dict.get("hiragana", "").strip(),
+ english=value_dict.get("english", "").strip(),
+ meanings=value_dict.get("meanings", "").strip()
+ ))
+
+ return entries
+
+def _entry_to_row(entry: Entry, delimiter: str = "ยง") -> str:
+ s = delimiter.join([entry.kanji, entry.hiragana, entry.english, entry.meanings])
+ return f"{s}\n"
+
+def write_to_file(path_str: str, entries: list):
+ p = path.join(path_str)
+
+ lines = map(_entry_to_row, entries)
+
+ with open(p, "w") as f:
+ f.writelines(lines)