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

逆向最大匹配分词算法C#

2015-11-02 19:51 645 查看
逆向顺序

句子:大家好我叫XX我是一名程序员

程序员  ->  序员  ->  员

名程序  ->  程序  ->  序

一名程  ->  名程  ->  程

是一名  ->  一名  ->  名

我是一  ->  是一  ->  一

X我是   ->  我是  ->  是

XX我   ->  X我  ->  我

叫XX   ->  XX   ->  X

我叫X   ->  叫X  ->  X

好我叫  ->  我叫  ->  叫

家好我  ->  好我  ->  我

大家好  ->  家好  ->  好

大家   ->  家



class Program
{
public static HashSet<string> dictionary = new HashSet<string>();

static void Main(string[] args)
{
Initail();
List<string> list = new List<string>();
string s = "大家好我叫XX我是一名程序员";
string[] sentences = s.Split(',');
int max = 3;
for (int i = 0; i < sentences.Length; i++)
{
string str = sentences[i];
int start = sentences[i].Length - max;
int len = sentences[i].Length - start;
while (len > 0)
{
string subWord = sentences[i].Substring((start < 0 ? 0 : start), len);
Console.WriteLine(subWord);
if (Search(subWord))
{
list.Add(subWord);
start = start - max;
if (start < 0)
{
len = start < 0 ? max + start : max;
}
}
else
{
int k = 1;
bool flag = false;
string tempWord = null;
for (; k <= subWord.Length - 1; k++)
{
tempWord = subWord.Substring(k);
Console.WriteLine(tempWord);
if (Search(tempWord))
{
flag = true;
list.Add(tempWord);
break;
}
}
if (flag)
{
start = start - tempWord.Length;
}
else
{
start--;
}
len = start < 0 ? max + start : max;
}
}
}
foreach (string x in list)
{
Console.WriteLine(x);
}
Console.ReadKey();
}

public static void Initail()
{
dictionary.Add("大家");
dictionary.Add("好");
dictionary.Add("我");
dictionary.Add("一名");
dictionary.Add("程序员");
dictionary.Add("nick");
}

public static bool Search(string word)
{
return dictionary.Contains(word);
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: