51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
||
# ztree-search · 光湖编号树模糊查号器(试点 v0)
|
||
# 用法: python3 ztree-search.py <关键字...> 例: python3 ztree-search.py 充钱
|
||
# 规则: 先精确命中节点语义锚,再模糊命中(子串)节点字段,未命中升根锚;
|
||
# 返回编号节点+一句话事实+路径,不返回全文——看图不读卷。
|
||
import json, sys, pathlib
|
||
|
||
ROOT = pathlib.Path(__file__).parent
|
||
|
||
def load_trees():
|
||
trees = []
|
||
for p in sorted(ROOT.glob("*/" )):
|
||
for f in p.glob("*.tree.json"):
|
||
trees.append(json.loads(f.read_text()))
|
||
return trees
|
||
|
||
def score(node, keys):
|
||
hay_anchors = " ".join(node.get("anchors", []))
|
||
hay_all = json.dumps(node, ensure_ascii=False)
|
||
s = 0
|
||
for k in keys:
|
||
if k in hay_anchors: s += 3 # 语义锚精确
|
||
elif k in hay_all: s += 1 # 字段模糊
|
||
return s
|
||
|
||
def main():
|
||
keys = [a for a in sys.argv[1:] if a != "-h"]
|
||
if not keys or "-h" in sys.argv:
|
||
print("用法: python3 ztree-search.py <关键字...>"); return
|
||
trees = load_trees()
|
||
hits = []
|
||
for t in trees:
|
||
root_hit = any(k in " ".join(t.get("anchors", [])) + t["title"] for k in keys)
|
||
for n in t["nodes"]:
|
||
s = score(n, keys)
|
||
if s: hits.append((s, t["tree_id"], n))
|
||
if root_hit and not hits:
|
||
print(f"〔命中树根〕{t['tree_id']} {t['title']} —— 整棵树相关,逐节点看树卷")
|
||
return
|
||
if not hits:
|
||
print("未命中任何编号节点。换个关键字,或该事尚未入树。"); return
|
||
hits.sort(key=lambda x: -x[0])
|
||
for s, tid, n in hits[:6]:
|
||
line = f"◆ {n['id']} {n.get('title','')}({tid})"
|
||
if n.get("fact"): line += f"\n 事实: {n['fact']}"
|
||
if n.get("path"): line += f"\n 路径: {n['path']}"
|
||
if n.get("next"): line += f"\n 下一步: {n['next']}"
|
||
print(line)
|
||
|
||
if __name__ == "__main__":
|
||
main()
|