2 个版本
0.1.1 | 2021年4月2日 |
---|---|
0.1.0 | 2021年4月1日 |
#1820 in 文本处理
19KB
325 行
Nutrimatic 索引文件读取器,适用于 Rust
这是一个用于读取存储在 trie 中的语言频率数据的 Nutrimatic 索引文件的 Rust 库。
lib.rs
:
一个用于读取 Nutrimatic 索引文件的 API。
有关文件格式的完整描述,请参阅 Nutrimatic 源代码中的 index.h 或创建索引文件的说明 README。
索引文件以一个包含文件内容的 &[u8]
形式接受;通常,这将通过在磁盘上对文件进行内存映射(当然,如果它适合内存,也可以完全读取索引文件)来创建。
索引文件描述了一个字符串 trie;边以字符(ASCII 空格、数字和字母)标记,每个节点存储以节点前导字符序列开始的短语在某个语料库中的总频率。
此库不对索引文件进行一致性检查。如果您尝试使用无效的文件,您将看到随机的 panic 或垃圾结果(但不会造成不安全)。不要这样做!
示例
use nutrimatic::Node;
// Collect all phrases in the trie in alphabetical order along with their
// frequencies.
fn collect(node: &Node, word: &mut String, out: &mut Vec<(String, u64)>) {
for child in &node.children() {
// The space indicates that this transition corresponds to a word
// boundary.
if child.ch() == ' ' as u8 {
out.push((word.clone(), child.freq()));
}
word.push(child.ch() as char);
collect(&child, word, out);
word.pop();
}
}
fn main() {
// This buffer describes a trie containing the words "ru" and "st"; a
// trie would normally be generated ahead of time by external tools. The
// byte values are written a bit oddly to hint at each one's purpose in
// the serialization.
let buf: &[u8] = &[
' ' as u8, 17, 0x00 | 1,
'u' as u8, 17, 0, 0x80 | 1,
' ' as u8, 18, 0x00 | 1,
't' as u8, 18, 0, 0x80 | 1,
'r' as u8, 17, 7, 's' as u8, 18, 0, 0x80 | 2,
];
let root = Node::new(buf);
let mut words = vec![];
collect(&root, &mut String::new(), &mut words);
assert_eq!(words, vec![("ru".to_owned(), 17), ("st".to_owned(), 18)]);
}
依赖项
~120KB