| Crates.io | pinyinchch |
| lib.rs | pinyinchch |
| version | 0.2.0 |
| created_at | 2026-01-03 17:07:56.292105+00 |
| updated_at | 2026-01-04 05:46:28.804852+00 |
| description | 一个拼音转汉字的工具库 |
| homepage | |
| repository | https://github.com/ixmoyren/pinyinchch |
| max_upload_size | |
| id | 2020476 |
| size | 68,630 |
一个拼音转汉字的工具库。
这是一个用 Rust 重写的 Pinyin2Hanzi 库,支持两种模型:
如果使用 hmm 的 Viterbi 算法进行拼音到汉字的转换,那么需要启用 hmm 功能。
cargo add pinyinchch -F hmm
如果使用默认提供的 hmm 模型,则需要引入 pinyinchch-model-hmm
cargo add pinyinchch-model-hmm
如果想自己实现一个拼音到汉字的 hmm 模型,那么需要引入 pinyinchch-type, 并且实现 Hmm trait
cargo add pinyinchch-type
如果使用 dag 的动态规划算法进行拼音到汉字的转换,那么需要启用 dag 功能。
cargo add pinyinchch -F dag
如果需要使用默认提供的 dag 模型,则需要引入 pinyinchch-model-dag
cargo add pinyinchch-model-dag
如果想自己实现一个拼音到汉字的 dag 模型,那么需要引入 pinyinchch-type, 并且实现 dag trait
cargo add pinyinchch-type
use pinyinchch::hmm::viterbi;
use pinyinchch::pinyin::pinyin_split_by_trie_tokenizer;
use pinyinchch_model_hmm::DefaultHmm;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 创建 HMM 实例
let hmm = DefaultHmm::default();
let pinyin = "nihao";
// 对拼音字符串进行拆分
let pinyin_split_str = pinyin_split_by_trie_tokenizer(pinyin);
let pinyin_seq = pinyin_split_str.split(" ").collect::<Vec<_>>();
// 使用 Viterbi 算法,返回 2 个候选结果,不使用对数概率
let result = viterbi(&hmm, &pinyin_seq, 2, false, 3.14e-200);
println!("HMM结果:");
for item in &result {
println!("分数: {}, 路径: {:?}", item.score(), item.path());
}
// 使用对数概率
let result_log = viterbi(&hmm, &pinyin_seq, 2, true, 3.14e-200);
println!("\nHMM结果 (对数概率):");
for item in &result_log {
println!("分数: {}, 路径: {:?}", item.score(), item.path());
}
Ok(())
}
use pinyinchch::dag::dispatch;
use pinyinchch_model_dag::DefaultDag;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 创建DAG参数实例
let dag_params = DefaultDag::default();
// 测试拼音转汉字
let pinyin_list = vec!["ni", "hao"];
// 使用DAG算法,返回2个候选结果,不使用对数概率
let result = dispatch(&dag_params, &pinyin_list, 2, false);
println!("DAG结果:");
for item in &result {
println!("分数: {}, 路径: {:?}", item.score(), item.path());
}
// 使用对数概率
let result_log = dispatch(&dag_params, &pinyin_list, 2, true);
println!("\nDAG结果 (对数概率):");
for item in &result_log {
println!("分数: {}, 路径: {:?}", item.score(), item.path());
}
Ok(())
}
本库使用预训练的模型数据,包括:
hmm_py2hz.json: 拼音到汉字的映射hmm_start.json: 起始概率hmm_emission.json: 发射概率hmm_transition.json: 状态转移概率dag_char.json: 单字拼音数据dag_phrase.json: 词组拼音数据运行测试:
cargo test
许可任你喜欢选择下面任一种,或者两种都选
除非您另有明确说明,否则任何您提交的代码许可应按上述 Apache 和 MIT 双重许可,并没有任何附加条款或条件。