近来需要做一些从中文文本中提取关键字(关键字自定义)的操作,偶然间了解了AC自动机算法,而网上的算法大多是基于英文实现的,所以也只是适用于英文提取关键字,因此最近研究了一下中文AC自动机的实现,记录下自己的思路,以期与大家共勉。
关于AC自动机,网上也已经是有了许多非常详细的介绍,比较关键的两步就是trie树和fail指针的构建,在这里也不再赘述,不清楚的可以去https://bestsort.cn/2019/04/28/402/。下面综合代码讲解一下我个人的实现方法,我使用java语言实现。
首先呢,是自定义一些关键字,为了方便统一操作,我们将关键字存入以UTF-8编码的txt文本中,每一行存一个关键字。不同类型的关键字存入不同的txt文本中,这里主要是适应于我个人的需要,用于区分关键字的类型,方便以后当做某种类型的参数去处理。
第一步,我构建一种新的数据结构,对该数据结构,每一个数据都有关键字和类型两个属性。
public class TypeKey {
public String ikey;//关键字
public String itype;//类型
}
第二步,我从不同的文本分别读出里面所有的关键字,并给同一文本里的关键字以相同的类型标记。
List<TypeKey> strings = new ArrayList<>();//储存关键字和类型的数组
String type1 = "time";//每一种type都对应着一种类型,同时对应一个txt文本
String type2 = "attr";
String type3 = "machine";
String type4 = "place";
String type5 = "order";
File timeKey = new File("D:\\dict\\time.txt");
File attrKey = new File("D:\\dict\\attr.txt");
File machineKey = new File("D:\\dict\\machine.txt");
File placeKey = new File("D:\\dict\\place.txt");
File orderKey = new File("D:\\dict\\order.txt");
String str = null;
BufferedReader brt = new BufferedReader(new InputStreamReader(new FileInputStream(timeKey), "UTF-8"));
while((str = brt.readLine())!=null){
String time = str;
TypeKey tk = new TypeKey();
tk.ikey = time;
tk.itype = type1;
strings.add(tk);
}
BufferedReader bra = new BufferedReader(new InputStreamReader(new FileInputStream(attrKey), "UTF-8"));
while((str = bra.readLine())!=null){
String attr = str;
TypeKey tk = new TypeKey();
tk.ikey = attr;
tk.ity