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; }}