您的位置:首页 > 编程语言

最大匹配算法实现中文分词(讲解+代码)

2014-09-23 22:04 701 查看
正向最大匹配算法实现中文分词代码下载

反向最大匹配算法实现中文分词代码下载.

最大匹配算法实现中文分词代码执行过程介绍

最大匹配算法实现中文分词讲解英文版

我的训练语料、测试语料都来自 中文分词评测语料

最大匹配算法,首先要根据训练语料训练出字典,然后再根据训练出来的字典实现中文分词。

首先读取训练语料,由于训练语料的句子都用双空格(" ")隔开,所以读取数据,遇到空格就将两空格之间的内容识别成一个词,并存进set里。

set是C++ STL的一个模版类,set具有不数据不重复的性质,所以同一个词语不会被存进set两次,特别好用。

这里仅插入代码片段,全部代码请到上面的下载地址下载。

while (!trainfile.eof())
{
//Read one sentence in the train corpus file.
getline(trainfile,trainsentence,'\n');
//cout<<trainsentence<<endl;
int cur_sen_length=trainsentence.length();
int wordlocation1=0;
int wordlocation2=0;
//Scan the sentence which have been read currently.
for (int i=0;i<cur_sen_length;i++)
{
// If encounter two space successively, then recognize the character sequence between  two spaces as a word.
if (trainsentence[i]==' ')
{
trainword=trainsentence.substr(wordlocation1,wordlocation2-wordlocation1);
//cout<<trainword<<endl;
// Insert the word into the "TrainSet" set.
TrainSet.insert(trainword);
wordlocation1=wordlocation2+1;
}
wordlocation2++;
}
}


然后,用迭代器将set的内容输出到dictionary.txt

ofstream dict("dictionary.txt");
set<string>::iterator iter;
for (iter=TrainSet.begin();iter!=TrainSet.end();iter++)
{
dict<<* iter<<endl;
}


最大匹配算法就是通过扫描句子,根据字典的词语,找到句子的最长匹配词语,然后加入分隔符,继续扫描找到下一个最长匹配词语,直到句子结束。

由于我假定一个中文词语的最大长度为8,故先截取句子的前八个字,看能不能在字典里找到匹配的,如果可以就加入分隔符,不可以就减少字序列的长度,继续看能不能在字典里找到匹配的,如此反复,直到匹配,或截取的字序列只剩一个字,加入分隔符。

详细代码可参考本文的代码下载地址。

你也可以在我的github上找到的我代码:

正向最大匹配算法实现中文分词代码下载

反向最大匹配算法实现中文分词代码下载

有任何疑问或发现程序bug欢迎联系。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: