#!/usr/bin/env python3"""日付ブロックごとの行数・バイト数と、head -N の切れ目がどこに落ちるかを出す。"""import reimport syspath, head_n = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 150lines = open(path, encoding="utf-8").read().split("\n")blocks, cur = [], Nonefor no, line in enumerate(lines, 1): m = re.match(r"## (\d{4}-\d{2}-\d{2})", line) if m: cur = {"date": m.group(1), "start": no, "lines": 0, "bytes": 0} blocks.append(cur) if cur: cur["lines"] += 1 cur["bytes"] += len(line.encode("utf-8")) + 1for b in blocks: print(f'{b["date"]} 開始{b["start"]:>4}行 {b["lines"]:>3}行 {b["bytes"]:>5}B {b["bytes"]/b["lines"]:>6.1f}B/行')total = sum(len(l.encode("utf-8")) + 1 for l in lines)got = sum(len(l.encode("utf-8")) + 1 for l in lines[:head_n])print(f"head -{head_n}: {got}B / 全体 {total}B ({got/total:.0%})")cut = next((b for b in reversed(blocks) if b["start"] <= head_n), None)if cut: print(f'切れ目は {cut["date"]} ブロックの {head_n - cut["start"] + 1} 行目: {lines[head_n-1][:40]}')
#!/usr/bin/env python3"""日次メモを「日付ブロック」単位で読む。最新日は全文、過去日は指定したセクション(A〜G)だけを出す。使い方: refpeek.py <file> [過去日数=2] [残すセクション=AE] [バイト上限=8000]"""import reimport sysdef load_blocks(path): blocks, cur = [], None with open(path, encoding="utf-8") as f: for line in f.read().split("\n"): m = re.match(r"## (\d{4}-\d{2}-\d{2})", line) if m: cur = {"date": m.group(1), "lines": [line]} blocks.append(cur) elif cur is not None: cur["lines"].append(line) return blocksdef pick_sections(lines, keep): out, on = [lines[0]], True for line in lines[1:]: m = re.match(r"### ([A-G])\.", line) if m: on = m.group(1) in keep if on: out.append(line) return outdef main(path, past_days=2, keep="AE", budget=8000): blocks = load_blocks(path) if not blocks: sys.exit("FATAL: 日ブロック見出し (## YYYY-MM-DD) が0件。形式が変わった可能性") out = list(blocks[0]["lines"]) for b in blocks[1:1 + past_days]: out += pick_sections(b["lines"], set(keep)) text = "\n".join(out) size = len(text.encode("utf-8")) note = "" if size <= budget else f" 上限{budget}超過" sys.stderr.write(f"blocks={1 + min(past_days, len(blocks) - 1)} bytes={size}{note}\n") print(text)if __name__ == "__main__": a = sys.argv main(a[1], int(a[2]) if len(a) > 2 else 2, a[3] if len(a) > 3 else "AE", int(a[4]) if len(a) > 4 else 8000)