C#中有丰富的类库,在汉字的处理问题上有较大的优势。
这次使用的是最大逆向分词,与昨天的正向分词,大同小异。点击打开链接
完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections;
namespace 最大逆向分词
{
class Program
{
static void Main(string[] args)
{
string text = "";
string path="E:\\data\\yuanwen.txt";
FileStream fs = File.OpenRead(path);
StreamReader sr = new StreamReader(fs, Encoding.Default);
text = text + sr.ReadLine();
Console.WriteLine(text);
sr.Close();
fs.Close();//读取文本结束,以上
char[] words = text.ToCharArray();//将文本放进数组
int wholelen = words.Length;
Console.WriteLine(wholelen);//数组的总长度为231,实际227字,说明空格被计入。
string mystr;//用来分词
OleDbConnection myconn = new OleDbConnection();
OleDbCommand mycmd = new OleDbCommand();
mystr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=words.mdb";
myconn.ConnectionString = mystr;
myconn.Open();
mycmd.Connection = myconn;
if (myconn.State == ConnectionState.Open)
Console.WriteLine("已成功连入数据库");
else
Console.WriteLine("未成功连入数据库");//连入数据库,以上
string cutword = null,mysql,output=" ";
int front = wholelen - 8, rear = wholelen, cutlen = 8,i=0;
while(front>0)
{
while(front!=rear)
{
cutword = null;
for(i=front;i<rear;i++)
cutword+=words[i];
mysql = "SELECT word FROM words WHERE word='" + cutword + "'";
mycmd.CommandText = mysql;
if (mycmd.ExecuteScalar() != null)
{
break;//匹配成功,跳出减字的循环
}
front++;//匹配不成功,则继续减字
}
output = output.Insert(0, cutword + "/");
rear -= cutword.Length;
front = rear - 8;
}
int n;
cutword = null;
while(rear>0)
{
while(rear!=front)
{
cutword = null;
for (n = front; n < rear; n++)
cutword += words[n];
mysql = "SELECT word FROM words WHERE word='" + cutword + "'";
mycmd.CommandText = mysql;
if (mycmd.ExecuteScalar() != null)
{
break;//匹配成功,跳出减字的循环
} front++;//匹配不成功,则继续减字
}
output = output.Insert(0, cutword + "/");
rear -= cutword.Length;
front = 1;
}
Console.WriteLine(output);
}
}
}
输出
与正向分词的相同点:
①连入txt,access方法一样
②待切字段仍然用front,rear来标记
不同点:
①最开始rear标记的文章尾字,front标记的是rear前的第八个字。第一个切的字段为:“社会而努力奋斗。”与数据库匹配,不成功,front++,cutword变成“会而努力奋斗。”
继续匹配,不成功,再front++;直至切除一个词,或者cutword只剩一个字,这时候便要切下来。注意,这里使用了insert方法,来保证输出时不会是相反的文章顺序。
错误示范:/。/努力奋斗/而/小康社会/建成/全面/
这里的insert方法避免了上述现象的产生。