Something went wrong. Try again.
An app for learning Chinese characters hanzi.bpev.me
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163#!/usr/bin/env python3"""Shared helpers for Hanzi data scripts."""
from __future__ import annotations
import csvimport jsonfrom pathlib import Pathfrom typing import Any, Iterable
ROOT = Path(__file__).resolve().parents[2]DATA_ROOT = ROOT / "data"GEN_ROOT = ROOT / "www" / "static" / "gen"
def data_path(*parts: str) -> Path: return DATA_ROOT.joinpath(*parts)
def gen_path(*parts: str) -> Path: return GEN_ROOT.joinpath(*parts)
def read_text(*parts: str) -> str: return data_path(*parts).read_text(encoding="utf-8")
def write_text(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8")
def read_tsv(*parts: str) -> list[dict[str, str]]: with data_path(*parts).open("r", encoding="utf-8", newline="") as f: return [{key: value or "" for key, value in row.items() if key is not None} for row in csv.DictReader(f, delimiter="\t")]
def read_tsv_rows(path: Path) -> tuple[list[str], list[list[str]]]: with path.open("r", encoding="utf-8", newline="") as f: reader = csv.reader(f, delimiter="\t") rows = list(reader) if not rows: return [], [] return rows[0], rows[1:]
def write_tsv_rows(path: Path, headers: list[str], rows: list[list[str]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8", newline="") as f: writer = csv.writer(f, delimiter="\t", lineterminator="\r\n") writer.writerow(headers) writer.writerows(rows)
def write_json(path: Path, value: Any, prod: bool = False) -> None: path.parent.mkdir(parents=True, exist_ok=True) if prod: text = json.dumps(value, ensure_ascii=False, separators=(",", ":")) else: text = json.dumps(value, ensure_ascii=False, indent=2) path.write_text(text, encoding="utf-8")
def copy_file(src: Path, dest: Path) -> None: import shutil
dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dest)
def iter_files(root: Path) -> Iterable[Path]: if not root.exists(): return [] return sorted(path for path in root.rglob("*") if path.is_file())
def parse_records(text: str, separator: str = "\t") -> list[list[str]]: """Parse lazy-quoted records, preserving the former sentence-import semantics.
A bare quote inside a quoted field is literal, not a closing quote. This matters for malformed Tatoeba exports: csv.reader otherwise changes which sentences (and IDs) survive the length filter. """ text = text.removeprefix("\ufeff") raw_lines = text.split("\n") if text.endswith("\n"): raw_lines.pop() lines = iter(raw_lines)
def next_line() -> str | None: line = next(lines, None) return line.removesuffix("\r") if line is not None else None
records = [] while (line := next_line()) is not None: if not line: continue fields = [] while True: if not line.startswith('"'): field, sep, line = line.partition(separator) fields.append(field) if sep: continue break line = line[1:] field = "" while True: before, quote, after = line.partition('"') field += before if not quote: following = next_line() if following is None: fields.append(field) line = "" more = False break field += "\n" line = following elif after.startswith('"'): field += '"' line = after[1:] elif after.startswith(separator): fields.append(field) line = after[len(separator):] more = True break elif not after: fields.append(field) more = False break else: field += '"' line = after if not more: break records.append(fields) return records
def js_parse_int(value: str) -> int | None: value = value.lstrip("\ufeff \t\n\r\v\f") if not value: return None sign = 1 if value[0] in "+-": if value[0] == "-": sign = -1 value = value[1:] radix = 16 if value.lower().startswith("0x") else 10 if radix == 16: value = value[2:] digits = "0123456789abcdef"[:radix] n = 0 any_digit = False for c in value.lower(): if c not in digits: break any_digit = True n = n * radix + digits.index(c) return sign * n if any_digit else None