接下来,我把扩展Lucene.net标准分词器所写的核心代码,主要包含三个函数,它们分别实现装载词典,载取连续中文字段,中文词组分词算法功能.

/**//*
#region 加载中文词典
public void LoadDirectory(string path)
{
if(!File.Exists("words.txt"))
return;
TextReader tr_words=new StreamReader("words.txt",System.Text.Encoding.Default);
System.Diagnostics.Debug.Write("begin read words");
if(directory==null)
{
directory=new System.Collections.Hashtable();
try
{
string word=null;
while((word=tr_words.ReadLine())!=null)
{
try
{
if(directory[word]==null)
{
directory.Add(word,word);
}
}
catch(SystemException ex_)
{
}
}
}
catch(SystemException ex)
{
}
}
#endregion
}
#region 截取一段连续中文字段
private void InitChinessText()
{
textlengh=0;
cn_index=0;
chinesstext[0]=token.image;
textlengh++;
cn_start=token.beginColumn;
isCnToken=true;
bool isCN= true;
while(isCN&&textlengh<255)
{ token=token_source.GetNextToken();
if(token.kind!=0)
{
isCN=Char.GetUnicodeCategory(token.image,0).Equals(System.Globalization.UnicodeCategory.OtherLetter);
}
else
isCN=false;
if(isCN)
{
chinesstext[textlengh]=token.image;
textlengh++;
}
else
{
cn_end_token=token;
}
}
if(textlengh>=4)
{
wordlengh=4;
}
else
wordlengh=textlengh;
}
#endregion
#region 实现中文分词算法
private string GetNextTokenText()
{ string text=null;
if(wordlengh==4)
{
text=chinesstext[cn_index]+chinesstext[cn_index+1]+chinesstext[cn_index+2]+chinesstext[cn_index+3];
if(directory[text]!=null)
{
}
wordlengh--;
}
if(wordlengh==3)
{
text=chinesstext[cn_index]+chinesstext[cn_index+1]+chinesstext[cn_index+2];
wordlengh--;
if(directory[text]!=null)
{
goto return_;
}
}
if(wordlengh==2)
{
text=chinesstext[cn_index]+chinesstext[cn_index+1];
wordlengh--;
if(directory[text]!=null)
{
goto return_;
}
}
if(wordlengh==1)
{
text=chinesstext[cn_index];
cn_index++;
if((textlengh-cn_index)>=4)
{
wordlengh=4;
}
else
if((textlengh-cn_index)==0)
{
isCnToken=false;
jj_ntk=cn_end_token.kind;
token=new Token();
token.next=cn_end_token;
}
else
{
wordlengh=textlengh-cn_index;
}
}
return_:
return text;
}
#endregion
*/
结束,谢谢你的阅读.
作者:游培尊
联系方式:Email:
Youpeizun126@126.com