这几天在研究中文分词,目前已经研究试验了基于词典的常用中文分词算法,包括正向最大匹配、逆向最大匹配、整词二分法、基于tire的中文分词、逐词二分法、双字多字hash的方法,稍后的文章会提及中文分词的方法和程序。此篇文章是基于tire的中文分词中检索树的实现,希望对tire感兴趣或者想研究中文分词的朋友有所帮助,仅做交流。 firstChHash.h头文件内容: /* /* 首字hash方法: 在整词二分法,基于Trie树的分词方法,逐字二分法,多次 背景知识:GB2312标准共收录6763个汉字,其中一级汉字3755个,二级汉字3008个. 举例来说,“啊”字是GB2312之中的第一个汉字,它的区位码就是1601。 为了区分汉字字符和ascii码,汉字的区码和位码都加上了OxA0,所以最高位都为1, // 从上表可以看出,GBK共提供了23,940字的编码空间, 实际定义了 21,886汉字,可用户定义1,894汉字。双字节编码规则如下: 第一字节 0x81-0xFE /* 首字hash函数1,针对gb2312拥有的99.5%的常用汉字的hash int index = sectionIndex * 94 + locationIndex; //gb2312每区94个字符,这个保证hash的结果和区位码是一一对应的 return index; return index; trieTree.h头文件内容: #include <vector> /* 检索树节点定义 */ /* 检索树类的定义 */ /* 根据区位码比较2个汉字序列的大小 /* 汉字的二分查找 */ /* 特殊二分查找,如果在有序序列中没有找到指定元素,返回该元素应该被插入的位置 */ /* 有序序列的插入,返回插入的位置 */ 实现和测试文件: // trieTree.cpp : Defines the entry point for the console application. #include "stdafx.h" /* 根据区位码比较2个汉字序列的大小 if ( (firstIndex >= 0) && (secondIndex >= 0) && (firstIndex < secondIndex) ) //2个首字都是gb2312的常用汉字 /* 汉字的二分查找 */ return -1; /* 特殊二分查找,如果在有序序列中没有找到指定元素,返回该元素应该被插入的位置 */ return insertPoint; /* 有序序列的插入,返回插入的位置 */ return insertPoint; /* 增添新字符串 */ return *this; /* 删除指定字符串 */ //下面统计每个汉字的分支 if ( *s == '/0' ) //当前有多路分支的字是最后一个字,最后一个字有多路分支,只删除该词的结尾符即可 return *this; /* 在检索树中查找指定字符串 */ return true; //all path return /* 在检索树中检索单独汉字,如果存在返回子检索树 */ int main() return 0; |
中文分词中的trie检索树实现
最新推荐文章于 2023-02-14 19:32:58 发布
原贴:http://hi.baidu.com/cuifenghui/blog/item/d66ff3360198db350b55a964.html
中文分词中的trie检索树实现
2008-02-27 17:29