2、长度大于4个中文字符,则取字符串最右边的4个中文字符,作为候选词;否则取出整个字符串作为候选词;4、在词典中查找这个候选词,如果查找失败,则去掉这个候选词的最左字,重复这步进行查找,直到候选词为1个中文字符;5、将候选词从字符串中取出、删除,回到第3步直到字符串为空;6、回到第2步直到语料已读完。(二)程序设计查找算法:哈希表汉字编码格式:UTF-8程序流程图:NOYESNONONONOYESYESYESYES匹配结束匹配结束匹配结束源代码:#include 3、t;#include 4、mespace_gnu_cxxtemplate<>structhash 5、ing,int>sipair;ifstreaminfile("CoreDict.txt.utf8");if(!infile.is_open()cerr<<"Unabletoopeninputfile:"<<"wordlexicon"<<"-bailingout!"< 6、读入词典的每一行并将其添加入哈希中istringstreamistr(strtmp);istr>>word;/读入每行第一个词wordhash.insert(sipair(word,1);/插入到哈希中infile.close();/删除语料库中已有的分词空格,由本程序重新分词stringdel_space(strings1)intp1=0,p2=0;intcount;strings2;while(p2 7、r(p1,p2-p1);p2+;p1=p2;elsep2+;s2+=s1.substr(p1,p2-p1);returns2;/用词典做逆向最大匹配法分词stringdict_segment(strings1)strings2=""/用s2存放分词结果while(!s1.empty()intlen=(int)s1.length();/取输入串长度if(len>MaxWordLength)/如果输入串长度大于最大词长len=MaxWordLength;/只在最大词长范围内进行处理string 8、w=s1.substr(s1.length()-len,len);intn=(wordhash.find(w)!=wordhash.end();/在词典中查找相应的词while(len>UTF8_CN_LEN&&n=0)/如果不是词len-=UTF8_CN_LEN;/从候选词左边减掉一个汉字,将剩下的部分作为候选词w=s1.substr(s1.length()-len,len);n=(wordhash.find(w)!=wordhash.end();w=w+Separator;s2 11、p2+=UTF8_CN_LEN;p1=p2;/endwhilereturns2;/在执行中文分词前,过滤半角空格以及其他非UTF-8字符stringseg_analysis(strings1)strings2;strings3=""intp1=0;intp2=0;intcount;while(p2 12、amp;14)14)&&p2 13、returns3;;intmain(intargc,char*argv)ifstreaminfile("1998-01-qiefen-file.txt.utf8");/打开输入文件if(!infile.is_open()/打开输入文件失败则退出程序cerr<<"Unabletoopeninputfile:"< 14、xit(-1);ofstreamoutfile1("result.txt.utf8");/确定输出文件if(!outfile1.is_open()cerr<<"Unabletoopenfile:SegmentResult.txt"<<"-bailingout!"< 15、_dict();finish=clock();duration=(double)(finish-start)/CLOCKS_PER_SEC;cout<<"词典读入完毕,耗时"<
《自然语言处理导论》中文分词程序实验报告(共9页)
THE END