summaryrefslogtreecommitdiffstats
path: root/kanji_info_fetcher/io.py
blob: bb0d69c2fb127b833734c702045e555f7c1fcd85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from os import path
from .entry import Entry

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(),
      note=value_dict.get("note", "").strip()
    ))

  return entries

def _entry_to_row(entry: Entry, delimiter: str = "§") -> str:
  s = delimiter.join([entry.kanji, entry.hiragana, entry.english, entry.meanings, entry.note])
  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)