cidian 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,180 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "cidian-rs"
7
+ version = "0.1.1"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "f539ec6a3f337ff43e7b0b12c74b07eea7b1a97829f7d20393c46463ae75dcc6"
10
+ dependencies = [
11
+ "thiserror",
12
+ "zlib-rs",
13
+ ]
14
+
15
+ [[package]]
16
+ name = "heck"
17
+ version = "0.5.0"
18
+ source = "registry+https://github.com/rust-lang/crates.io-index"
19
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
20
+
21
+ [[package]]
22
+ name = "libc"
23
+ version = "0.2.189"
24
+ source = "registry+https://github.com/rust-lang/crates.io-index"
25
+ checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
26
+
27
+ [[package]]
28
+ name = "once_cell"
29
+ version = "1.21.4"
30
+ source = "registry+https://github.com/rust-lang/crates.io-index"
31
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
32
+
33
+ [[package]]
34
+ name = "portable-atomic"
35
+ version = "1.15.0"
36
+ source = "registry+https://github.com/rust-lang/crates.io-index"
37
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
38
+
39
+ [[package]]
40
+ name = "proc-macro2"
41
+ version = "1.0.107"
42
+ source = "registry+https://github.com/rust-lang/crates.io-index"
43
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
44
+ dependencies = [
45
+ "unicode-ident",
46
+ ]
47
+
48
+ [[package]]
49
+ name = "py-cidian"
50
+ version = "0.1.0"
51
+ dependencies = [
52
+ "cidian-rs",
53
+ "pyo3",
54
+ ]
55
+
56
+ [[package]]
57
+ name = "pyo3"
58
+ version = "0.29.2"
59
+ source = "registry+https://github.com/rust-lang/crates.io-index"
60
+ checksum = "4688ddedf473e32662b9b067670129a8afb8c18e351482c70d62ba4a88171e8b"
61
+ dependencies = [
62
+ "libc",
63
+ "once_cell",
64
+ "portable-atomic",
65
+ "pyo3-build-config",
66
+ "pyo3-ffi",
67
+ "pyo3-macros",
68
+ ]
69
+
70
+ [[package]]
71
+ name = "pyo3-build-config"
72
+ version = "0.29.2"
73
+ source = "registry+https://github.com/rust-lang/crates.io-index"
74
+ checksum = "f41027e41b4bd03f6e60f9f417fe24a6341a6bb744edd62b6f709f2a52ea30e9"
75
+ dependencies = [
76
+ "target-lexicon",
77
+ ]
78
+
79
+ [[package]]
80
+ name = "pyo3-ffi"
81
+ version = "0.29.2"
82
+ source = "registry+https://github.com/rust-lang/crates.io-index"
83
+ checksum = "e591a95526fead067432c3b3a33fc74770b87b1e04e73671090d9c2055a2b327"
84
+ dependencies = [
85
+ "libc",
86
+ "pyo3-build-config",
87
+ ]
88
+
89
+ [[package]]
90
+ name = "pyo3-macros"
91
+ version = "0.29.2"
92
+ source = "registry+https://github.com/rust-lang/crates.io-index"
93
+ checksum = "73225868fc1cd84eef2c3c230ddb91273bf1de46aeb8a4248da76d32a0924a1c"
94
+ dependencies = [
95
+ "proc-macro2",
96
+ "pyo3-macros-backend",
97
+ "quote",
98
+ "syn 2.0.119",
99
+ ]
100
+
101
+ [[package]]
102
+ name = "pyo3-macros-backend"
103
+ version = "0.29.2"
104
+ source = "registry+https://github.com/rust-lang/crates.io-index"
105
+ checksum = "571575aa3749fa6216757dd47d2a3e7ef360f329a40f0666a9fbd14889024952"
106
+ dependencies = [
107
+ "heck",
108
+ "proc-macro2",
109
+ "quote",
110
+ "syn 2.0.119",
111
+ ]
112
+
113
+ [[package]]
114
+ name = "quote"
115
+ version = "1.0.47"
116
+ source = "registry+https://github.com/rust-lang/crates.io-index"
117
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
118
+ dependencies = [
119
+ "proc-macro2",
120
+ ]
121
+
122
+ [[package]]
123
+ name = "syn"
124
+ version = "2.0.119"
125
+ source = "registry+https://github.com/rust-lang/crates.io-index"
126
+ checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
127
+ dependencies = [
128
+ "proc-macro2",
129
+ "quote",
130
+ "unicode-ident",
131
+ ]
132
+
133
+ [[package]]
134
+ name = "syn"
135
+ version = "3.0.4"
136
+ source = "registry+https://github.com/rust-lang/crates.io-index"
137
+ checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f"
138
+ dependencies = [
139
+ "proc-macro2",
140
+ "quote",
141
+ "unicode-ident",
142
+ ]
143
+
144
+ [[package]]
145
+ name = "target-lexicon"
146
+ version = "0.13.5"
147
+ source = "registry+https://github.com/rust-lang/crates.io-index"
148
+ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
149
+
150
+ [[package]]
151
+ name = "thiserror"
152
+ version = "2.0.20"
153
+ source = "registry+https://github.com/rust-lang/crates.io-index"
154
+ checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
155
+ dependencies = [
156
+ "thiserror-impl",
157
+ ]
158
+
159
+ [[package]]
160
+ name = "thiserror-impl"
161
+ version = "2.0.20"
162
+ source = "registry+https://github.com/rust-lang/crates.io-index"
163
+ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
164
+ dependencies = [
165
+ "proc-macro2",
166
+ "quote",
167
+ "syn 3.0.4",
168
+ ]
169
+
170
+ [[package]]
171
+ name = "unicode-ident"
172
+ version = "1.0.24"
173
+ source = "registry+https://github.com/rust-lang/crates.io-index"
174
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
175
+
176
+ [[package]]
177
+ name = "zlib-rs"
178
+ version = "0.6.7"
179
+ source = "registry+https://github.com/rust-lang/crates.io-index"
180
+ checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
@@ -0,0 +1,42 @@
1
+ [package]
2
+ name = "py-cidian"
3
+ version = "0.1.0"
4
+ edition = "2024"
5
+ rust-version = "1.85"
6
+ publish = false
7
+ description = "Python bindings for cidian-rs"
8
+ readme = "README.md"
9
+ homepage = "https://github.com/Yousa-Mirage/py-cidian"
10
+ repository = "https://github.com/Yousa-Mirage/py-cidian"
11
+ license = "MIT"
12
+ include = [
13
+ "/Cargo.lock",
14
+ "/Cargo.toml",
15
+ "/LICENSE",
16
+ "/README.md",
17
+ "/pyproject.toml",
18
+ "/src/**/*.rs",
19
+ "/src/cidian/*.py",
20
+ "/src/cidian/*.pyi",
21
+ "/src/cidian/py.typed",
22
+ ]
23
+
24
+ [lib]
25
+ name = "_core"
26
+ crate-type = ["cdylib"]
27
+
28
+ [dependencies]
29
+ cidian-core = { package = "cidian-rs", version = "0.1" }
30
+ pyo3 = { version = "0.29", features = ["extension-module", "abi3-py310"] }
31
+
32
+ [lints.clippy]
33
+ expect_used = "deny"
34
+ unwrap_used = "deny"
35
+
36
+ [lints.rust]
37
+ dead_code = "deny"
38
+ warnings = "deny"
39
+
40
+ [profile.release]
41
+ codegen-units = 1
42
+ lto = true
cidian-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yousa-Mirage
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
cidian-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: cidian
3
+ Version: 0.1.0
4
+ Classifier: Development Status :: 3 - Alpha
5
+ Classifier: Programming Language :: Python :: 3
6
+ Classifier: Programming Language :: Rust
7
+ Classifier: Typing :: Typed
8
+ License-File: LICENSE
9
+ Summary: Fast parser for Chinese input method dictionaries
10
+ Keywords: chinese,dictionary,input-method,pinyin
11
+ Home-Page: https://github.com/Yousa-Mirage/py-cidian
12
+ Author-email: Yousa-Mirage <Yousa-Mirage@foxmail.com>
13
+ License-Expression: MIT
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
16
+
17
+ # py-cidian
18
+
19
+ <div align="center">
20
+
21
+ [![Python >= 3.10](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)](https://www.python.org/)
22
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
23
+
24
+ </div>
25
+
26
+ `py-cidian` 读取中文输入法词库,并把不同格式转换成统一的 Python 数据模型。目前支持以下格式:
27
+
28
+ | 格式 | 扩展名 | 来源 |
29
+ | ----- | -------- | ------- |
30
+ | SCEL | `.scel` | 搜狗 |
31
+ | QCEL | `.qcel` | QQ 拼音 |
32
+ | QPYD | `.qpyd` | QQ 拼音 |
33
+ | BDICT | `.bdict` | 百度 |
34
+ | BCD | `.bcd` | 百度 |
35
+
36
+ 底层解析由 Rust 库 [`cidian-rs`](https://github.com/Yousa-Mirage/cidian-rs) 完成。解析结果保持词条在源文件中的顺序,不会自动规范化、排序或去重。
37
+
38
+ `py-cidian` 与 [`r-cidian`](https://github.com/Yousa-Mirage/r-cidian) 提供相近的数据模型,适合把输入法词库转换为中文分词工具可使用的自定义词表。
39
+
40
+ ## 安装
41
+
42
+ 使用 uv 从 PyPI 安装:
43
+
44
+ ```sh
45
+ uv pip install cidian
46
+ ```
47
+
48
+ 如需从源码构建,可以克隆仓库后生成 wheel:
49
+
50
+ ```sh
51
+ git clone https://github.com/Yousa-Mirage/py-cidian.git
52
+ cd py-cidian
53
+ uv sync --locked
54
+ uv build --no-sources
55
+ ```
56
+
57
+ 从源码构建需要 Rust 1.85 或更高版本。生成的 wheel 使用 Python 3.10+ 稳定 ABI。
58
+
59
+ ## 使用说明
60
+
61
+ ### 从文件读取
62
+
63
+ `read_cidian()` 默认根据文件扩展名识别格式:
64
+
65
+ ```python
66
+ from cidian import read_cidian
67
+
68
+ dictionary = read_cidian("计算机科技.qcel")
69
+
70
+ print(dictionary.format)
71
+ # qcel
72
+
73
+ print(dictionary.metadata.name)
74
+ # 计算机名词
75
+
76
+ print(len(dictionary))
77
+ # 9646
78
+
79
+ print(dictionary.entries[0])
80
+ # Entry(word='阿里通', code=('a', 'li', 'tong'), weight=8)
81
+ ```
82
+
83
+ 当路径没有正确的扩展名时,可以显式指定格式。格式名不区分大小写,也可以带有开头的点:
84
+
85
+ ```python
86
+ dictionary = read_cidian("dictionary.bin", format=".QCEL")
87
+ ```
88
+
89
+ ### 从 bytes 加载
90
+
91
+ `load_cidian()` 把内存中的 `bytes` 直接交给 Rust 解析,不经过临时文件:
92
+
93
+ ```python
94
+ from pathlib import Path
95
+
96
+ from cidian import load_cidian
97
+
98
+ data = Path("计算机科技.qcel").read_bytes()
99
+ dictionary = load_cidian(data, format="qcel")
100
+ ```
101
+
102
+ 与文件读取不同,内存数据没有扩展名,因此必须提供 `format`。
103
+
104
+ ### 访问词条和元信息
105
+
106
+ 解析结果由 `Dictionary`、`Metadata` 和 `Entry` 数据类组成:
107
+
108
+ ```python
109
+ metadata = dictionary.metadata
110
+ print(metadata.name)
111
+ print(metadata.category)
112
+ print(metadata.description)
113
+ print(metadata.extra)
114
+
115
+ for entry in dictionary:
116
+ print(entry.word, entry.code, entry.weight)
117
+ ```
118
+
119
+ 其中:
120
+
121
+ - `Entry.word` 是原始词语;
122
+ - `Entry.code` 是由编码组件组成的元组,例如拼音音节;
123
+ - `Entry.weight` 是来源格式提供的可选权重;
124
+ - `Metadata.extra` 保存无法归入通用字段的来源特有元信息。
125
+
126
+ ### 导出词语
127
+
128
+ `write_words()` 按原始顺序把所有词语写入 UTF-8 文本文件,每行一个:
129
+
130
+ ```python
131
+ from cidian import write_words
132
+
133
+ write_words(dictionary, "words.txt")
134
+ ```
135
+
136
+ 目标文件已存在时默认抛出 `FileExistsError`。需要覆盖时显式传入:
137
+
138
+ ```python
139
+ write_words(dictionary, "words.txt", overwrite=True)
140
+ ```
141
+
142
+ ## 致谢
143
+
144
+ - 感谢 nopdan 的[输入法词库解析系列文章](https://nopdan.com/series/lexicon/)以及
145
+ [nopdan/rose](https://github.com/nopdan/rose) 蔷薇词库转换库;`cidian-rs` 的开发大量参考了这些资料。
146
+ - 感谢 qinwf/cidian 项目提供开发动机。
147
+ - `py-cidian` 的公开 API 和文档结构参考了 [`r-cidian`](https://github.com/Yousa-Mirage/r-cidian)。
148
+ - Python 绑定使用 [PyO3](https://github.com/PyO3/pyo3) 实现。
149
+
150
+ ## 许可证
151
+
152
+ MIT License
153
+
cidian-0.1.0/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # py-cidian
2
+
3
+ <div align="center">
4
+
5
+ [![Python >= 3.10](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)](https://www.python.org/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
+
8
+ </div>
9
+
10
+ `py-cidian` 读取中文输入法词库,并把不同格式转换成统一的 Python 数据模型。目前支持以下格式:
11
+
12
+ | 格式 | 扩展名 | 来源 |
13
+ | ----- | -------- | ------- |
14
+ | SCEL | `.scel` | 搜狗 |
15
+ | QCEL | `.qcel` | QQ 拼音 |
16
+ | QPYD | `.qpyd` | QQ 拼音 |
17
+ | BDICT | `.bdict` | 百度 |
18
+ | BCD | `.bcd` | 百度 |
19
+
20
+ 底层解析由 Rust 库 [`cidian-rs`](https://github.com/Yousa-Mirage/cidian-rs) 完成。解析结果保持词条在源文件中的顺序,不会自动规范化、排序或去重。
21
+
22
+ `py-cidian` 与 [`r-cidian`](https://github.com/Yousa-Mirage/r-cidian) 提供相近的数据模型,适合把输入法词库转换为中文分词工具可使用的自定义词表。
23
+
24
+ ## 安装
25
+
26
+ 使用 uv 从 PyPI 安装:
27
+
28
+ ```sh
29
+ uv pip install cidian
30
+ ```
31
+
32
+ 如需从源码构建,可以克隆仓库后生成 wheel:
33
+
34
+ ```sh
35
+ git clone https://github.com/Yousa-Mirage/py-cidian.git
36
+ cd py-cidian
37
+ uv sync --locked
38
+ uv build --no-sources
39
+ ```
40
+
41
+ 从源码构建需要 Rust 1.85 或更高版本。生成的 wheel 使用 Python 3.10+ 稳定 ABI。
42
+
43
+ ## 使用说明
44
+
45
+ ### 从文件读取
46
+
47
+ `read_cidian()` 默认根据文件扩展名识别格式:
48
+
49
+ ```python
50
+ from cidian import read_cidian
51
+
52
+ dictionary = read_cidian("计算机科技.qcel")
53
+
54
+ print(dictionary.format)
55
+ # qcel
56
+
57
+ print(dictionary.metadata.name)
58
+ # 计算机名词
59
+
60
+ print(len(dictionary))
61
+ # 9646
62
+
63
+ print(dictionary.entries[0])
64
+ # Entry(word='阿里通', code=('a', 'li', 'tong'), weight=8)
65
+ ```
66
+
67
+ 当路径没有正确的扩展名时,可以显式指定格式。格式名不区分大小写,也可以带有开头的点:
68
+
69
+ ```python
70
+ dictionary = read_cidian("dictionary.bin", format=".QCEL")
71
+ ```
72
+
73
+ ### 从 bytes 加载
74
+
75
+ `load_cidian()` 把内存中的 `bytes` 直接交给 Rust 解析,不经过临时文件:
76
+
77
+ ```python
78
+ from pathlib import Path
79
+
80
+ from cidian import load_cidian
81
+
82
+ data = Path("计算机科技.qcel").read_bytes()
83
+ dictionary = load_cidian(data, format="qcel")
84
+ ```
85
+
86
+ 与文件读取不同,内存数据没有扩展名,因此必须提供 `format`。
87
+
88
+ ### 访问词条和元信息
89
+
90
+ 解析结果由 `Dictionary`、`Metadata` 和 `Entry` 数据类组成:
91
+
92
+ ```python
93
+ metadata = dictionary.metadata
94
+ print(metadata.name)
95
+ print(metadata.category)
96
+ print(metadata.description)
97
+ print(metadata.extra)
98
+
99
+ for entry in dictionary:
100
+ print(entry.word, entry.code, entry.weight)
101
+ ```
102
+
103
+ 其中:
104
+
105
+ - `Entry.word` 是原始词语;
106
+ - `Entry.code` 是由编码组件组成的元组,例如拼音音节;
107
+ - `Entry.weight` 是来源格式提供的可选权重;
108
+ - `Metadata.extra` 保存无法归入通用字段的来源特有元信息。
109
+
110
+ ### 导出词语
111
+
112
+ `write_words()` 按原始顺序把所有词语写入 UTF-8 文本文件,每行一个:
113
+
114
+ ```python
115
+ from cidian import write_words
116
+
117
+ write_words(dictionary, "words.txt")
118
+ ```
119
+
120
+ 目标文件已存在时默认抛出 `FileExistsError`。需要覆盖时显式传入:
121
+
122
+ ```python
123
+ write_words(dictionary, "words.txt", overwrite=True)
124
+ ```
125
+
126
+ ## 致谢
127
+
128
+ - 感谢 nopdan 的[输入法词库解析系列文章](https://nopdan.com/series/lexicon/)以及
129
+ [nopdan/rose](https://github.com/nopdan/rose) 蔷薇词库转换库;`cidian-rs` 的开发大量参考了这些资料。
130
+ - 感谢 qinwf/cidian 项目提供开发动机。
131
+ - `py-cidian` 的公开 API 和文档结构参考了 [`r-cidian`](https://github.com/Yousa-Mirage/r-cidian)。
132
+ - Python 绑定使用 [PyO3](https://github.com/PyO3/pyo3) 实现。
133
+
134
+ ## 许可证
135
+
136
+ MIT License
@@ -0,0 +1,52 @@
1
+ [build-system]
2
+ requires = ["maturin>=1.10,<2"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "cidian"
7
+ version = "0.1.0"
8
+ description = "Fast parser for Chinese input method dictionaries"
9
+ readme = "README.md"
10
+ authors = [
11
+ { name = "Yousa-Mirage", email = "Yousa-Mirage@foxmail.com" }
12
+ ]
13
+ requires-python = ">=3.10"
14
+ license = "MIT"
15
+ keywords = ["chinese", "dictionary", "input-method", "pinyin"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Rust",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = []
23
+
24
+ [dependency-groups]
25
+ dev = [
26
+ "maturin>=1.10,<2",
27
+ "pytest>=8",
28
+ "ruff>=0.12",
29
+ "ty>=0.0.75",
30
+ ]
31
+
32
+ [tool.maturin]
33
+ module-name = "cidian._core"
34
+ python-packages = ["cidian"]
35
+ python-source = "src"
36
+ features = ["pyo3/extension-module"]
37
+
38
+ [tool.pytest.ini_options]
39
+ addopts = "-ra"
40
+ testpaths = ["tests"]
41
+
42
+ [tool.ruff]
43
+ line-length = 105
44
+ preview = true
45
+
46
+ [tool.uv]
47
+ cache-keys = [
48
+ { file = "pyproject.toml" },
49
+ { file = "Cargo.toml" },
50
+ { file = "Cargo.lock" },
51
+ { file = "src/**/*.rs" },
52
+ ]
@@ -0,0 +1,154 @@
1
+ """Read Chinese input-method dictionaries through :mod:`cidian-rs`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Mapping
6
+ from dataclasses import dataclass
7
+ from os import PathLike
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, Final
10
+
11
+ from ._core import CidianError, parse_bytes, parse_file
12
+
13
+ if TYPE_CHECKING:
14
+ from ._core import _Dictionary
15
+
16
+ SUPPORTED_FORMATS: Final = ("scel", "qcel", "qpyd", "bdict", "bcd")
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class Metadata:
21
+ """Metadata supplied by a source dictionary."""
22
+
23
+ name: str | None
24
+ category: str | None
25
+ description: str | None
26
+ extra: Mapping[str, str]
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Entry:
31
+ """A dictionary entry in its original source order."""
32
+
33
+ word: str
34
+ code: tuple[str, ...]
35
+ weight: int | None
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class Dictionary:
40
+ """A parsed dictionary with a common data model."""
41
+
42
+ metadata: Metadata
43
+ entries: tuple[Entry, ...]
44
+ format: str
45
+
46
+ def __iter__(self) -> Iterator[Entry]:
47
+ return iter(self.entries)
48
+
49
+ def __len__(self) -> int:
50
+ return len(self.entries)
51
+
52
+
53
+ def cidian_formats() -> tuple[str, ...]:
54
+ """Return the dictionary format identifiers accepted by :func:`read_cidian`."""
55
+
56
+ return SUPPORTED_FORMATS
57
+
58
+
59
+ def read_cidian(path: str | PathLike[str], *, format: str | None = None) -> Dictionary:
60
+ """Parse a supported Chinese input-method dictionary.
61
+
62
+ The source order is preserved. Entries are not normalized, sorted, or
63
+ deduplicated.
64
+ """
65
+
66
+ source = Path(path).expanduser()
67
+ selected_format = _normalize_format(format, source)
68
+ return _dictionary_from_raw(parse_file(str(source), selected_format))
69
+
70
+
71
+ def load_cidian(data: bytes, *, format: str) -> Dictionary:
72
+ """Parse a supported dictionary directly from bytes.
73
+
74
+ The source order is preserved. Entries are not normalized, sorted, or
75
+ deduplicated.
76
+ """
77
+
78
+ if not isinstance(data, bytes):
79
+ raise TypeError("data must be bytes")
80
+
81
+ selected_format = _normalize_format_name(format)
82
+ return _dictionary_from_raw(parse_bytes(data, selected_format))
83
+
84
+
85
+ def _dictionary_from_raw(raw: _Dictionary) -> Dictionary:
86
+ raw_metadata = raw["metadata"]
87
+
88
+ return Dictionary(
89
+ metadata=Metadata(
90
+ name=raw_metadata["name"],
91
+ category=raw_metadata["category"],
92
+ description=raw_metadata["description"],
93
+ extra=dict(raw_metadata["extra"]),
94
+ ),
95
+ entries=tuple(
96
+ Entry(word=word, code=tuple(code), weight=weight) for word, code, weight in raw["entries"]
97
+ ),
98
+ format=raw["format"],
99
+ )
100
+
101
+
102
+ def write_words(
103
+ dictionary: Dictionary,
104
+ path: str | PathLike[str],
105
+ *,
106
+ overwrite: bool = False,
107
+ ) -> Path:
108
+ """Write one entry word per UTF-8 line, preserving source order."""
109
+
110
+ if not isinstance(dictionary, Dictionary):
111
+ raise TypeError("dictionary must be a cidian.Dictionary")
112
+
113
+ destination = Path(path).expanduser()
114
+ if destination.exists() and not overwrite:
115
+ raise FileExistsError(f"{destination} already exists; pass overwrite=True to replace it")
116
+
117
+ words = "\n".join(entry.word for entry in dictionary.entries)
118
+ destination.write_text(f"{words}\n" if words else "", encoding="utf-8")
119
+ return destination
120
+
121
+
122
+ def _normalize_format(format: str | None, path: Path) -> str:
123
+ if format is None:
124
+ selected = path.suffix.removeprefix(".").lower()
125
+ if not selected:
126
+ raise ValueError("cannot infer dictionary format from a path without a suffix")
127
+ return _normalize_format_name(selected)
128
+
129
+ return _normalize_format_name(format)
130
+
131
+
132
+ def _normalize_format_name(format: str) -> str:
133
+ if not isinstance(format, str):
134
+ raise TypeError("format must be a string or None")
135
+
136
+ selected = format.removeprefix(".").lower()
137
+
138
+ if selected not in SUPPORTED_FORMATS:
139
+ supported = ", ".join(SUPPORTED_FORMATS)
140
+ raise ValueError(f"unsupported dictionary format {selected!r}; expected {supported}")
141
+ return selected
142
+
143
+
144
+ __all__ = [
145
+ "SUPPORTED_FORMATS",
146
+ "CidianError",
147
+ "Dictionary",
148
+ "Entry",
149
+ "Metadata",
150
+ "cidian_formats",
151
+ "load_cidian",
152
+ "read_cidian",
153
+ "write_words",
154
+ ]
@@ -0,0 +1,17 @@
1
+ from typing import TypedDict
2
+
3
+ class CidianError(Exception): ...
4
+
5
+ class _Metadata(TypedDict):
6
+ name: str | None
7
+ category: str | None
8
+ description: str | None
9
+ extra: dict[str, str]
10
+
11
+ class _Dictionary(TypedDict):
12
+ metadata: _Metadata
13
+ entries: list[tuple[str, list[str], int | None]]
14
+ format: str
15
+
16
+ def parse_file(path: str, format: str) -> _Dictionary: ...
17
+ def parse_bytes(data: bytes, format: str) -> _Dictionary: ...
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,88 @@
1
+ use std::collections::BTreeMap;
2
+
3
+ use pyo3::create_exception;
4
+ use pyo3::exceptions::{PyException, PyValueError};
5
+ use pyo3::prelude::*;
6
+ use pyo3::types::{PyDict, PyList, PyModule};
7
+
8
+ create_exception!(_core, CidianError, PyException);
9
+
10
+ /// Parse a supported dictionary file and return a Python-friendly data model.
11
+ #[pyfunction]
12
+ fn parse_file(py: Python<'_>, path: &str, format: &str) -> PyResult<Py<PyDict>> {
13
+ let dictionary = match format {
14
+ "scel" => cidian_core::scel::parse_file(path),
15
+ "qcel" => cidian_core::qcel::parse_file(path),
16
+ "qpyd" => cidian_core::qpyd::parse_file(path),
17
+ "bdict" => cidian_core::bdict::parse_file(path),
18
+ "bcd" => cidian_core::bcd::parse_file(path),
19
+ _ => {
20
+ return Err(PyValueError::new_err(format!(
21
+ "unsupported dictionary format {format:?}"
22
+ )));
23
+ }
24
+ }
25
+ .map_err(|error| CidianError::new_err(error.to_string()))?;
26
+
27
+ dictionary_to_dict(py, dictionary, format)
28
+ }
29
+
30
+ /// Parse supported dictionary data and return a Python-friendly data model.
31
+ #[pyfunction]
32
+ fn parse_bytes(py: Python<'_>, data: &[u8], format: &str) -> PyResult<Py<PyDict>> {
33
+ let dictionary = match format {
34
+ "scel" => cidian_core::scel::parse(data),
35
+ "qcel" => cidian_core::qcel::parse(data),
36
+ "qpyd" => cidian_core::qpyd::parse(data),
37
+ "bdict" => cidian_core::bdict::parse(data),
38
+ "bcd" => cidian_core::bcd::parse(data),
39
+ _ => {
40
+ return Err(PyValueError::new_err(format!(
41
+ "unsupported dictionary format {format:?}"
42
+ )));
43
+ }
44
+ }
45
+ .map_err(|error| CidianError::new_err(error.to_string()))?;
46
+
47
+ dictionary_to_dict(py, dictionary, format)
48
+ }
49
+
50
+ fn dictionary_to_dict(
51
+ py: Python<'_>,
52
+ dictionary: cidian_core::Dictionary,
53
+ format: &str,
54
+ ) -> PyResult<Py<PyDict>> {
55
+ let metadata = PyDict::new(py);
56
+ metadata.set_item("name", dictionary.metadata.name)?;
57
+ metadata.set_item("category", dictionary.metadata.category)?;
58
+ metadata.set_item("description", dictionary.metadata.description)?;
59
+ metadata.set_item("extra", extra_to_dict(py, dictionary.metadata.extra)?)?;
60
+
61
+ let entries = PyList::empty(py);
62
+ for entry in dictionary.entries {
63
+ entries.append((entry.word, entry.code, entry.weight))?;
64
+ }
65
+
66
+ let result = PyDict::new(py);
67
+ result.set_item("metadata", metadata)?;
68
+ result.set_item("entries", entries)?;
69
+ result.set_item("format", format)?;
70
+ Ok(result.unbind())
71
+ }
72
+
73
+ fn extra_to_dict(py: Python<'_>, extra: BTreeMap<String, String>) -> PyResult<Py<PyDict>> {
74
+ let result = PyDict::new(py);
75
+ for (key, value) in extra {
76
+ result.set_item(key, value)?;
77
+ }
78
+ Ok(result.unbind())
79
+ }
80
+
81
+ /// Native parsing primitives for the `cidian` Python package.
82
+ #[pymodule]
83
+ fn _core(module: &Bound<'_, PyModule>) -> PyResult<()> {
84
+ module.add("CidianError", module.py().get_type::<CidianError>())?;
85
+ module.add_function(wrap_pyfunction!(parse_bytes, module)?)?;
86
+ module.add_function(wrap_pyfunction!(parse_file, module)?)?;
87
+ Ok(())
88
+ }