现在的位置: 首页 > 综合 > 正文

c# 写了个正向匹配的分词算法

2012年09月29日 ⁄ 综合 ⁄ 共 1156字 ⁄ 字号 评论关闭

c# 写了个正向匹配的分词算法,思路很简单,每次从字符串中取一个词,至于词的长度,能够自己配置的,比如本文中的,

后偏差的意思是:当取到一个词时不立即社区该串字符,而是顺延Offset个字符,如该词库中的:共和,共和国 就是如此。

前偏差的意思是:同上当取到一个词时,并不重新从新位置开始,而是从指定偏差值的位置开始,如该词库中的:中华,华人。

明天继续完善,欢迎高手指定,谢谢! 

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    public ArrayList al = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = "中华人民共和国";
        al.Add("人民");
        al.Add("华人");
        al.Add("中华");
        al.Add("共和");
        al.Add("共和国");
        char[] chs = str.ToCharArray();

        Response.Write(SplitString(str));
        return;
    }

    int MinSize = 2;//最小词长
     int MaxSize = 4;//最大词长
    int Offset = 1;//后偏差
    int LOffset = 1;//前偏差
public string SplitString(string str) { string keys = string.Empty; char[] chs = str.ToCharArray(); int chsLen = chs.Length; string tempKey = string.Empty; for (int j = 0; j < chsLen; j++) { int CurrChLen = 0; int CurrOffset = 0; for (int i = j; i < chsLen; i++) { tempKey += chs[i].ToString(); CurrChLen++; if (CurrChLen < MinSize) { continue; } if (CurrChLen > MaxSize) { break; } if (al.Contains(tempKey)) { keys += tempKey + ","; if (CurrOffset < Offset) { j = i - 1; CurrOffset++; continue; } break; } if (CurrOffset > 0) { break; } } tempKey = string.Empty; } return keys; } }

 

抱歉!评论已关闭.