Syn Bot /OSCOVA 实体识别器(13)

Entity Recognizers

Oscova支持多种方式创建实体识别器,可以使用已知词汇,正则模式或者直接创建方法从请求中提取。

使用CreateRecognizer()方法就可以创建了,这个方式创建的识别器是大小写不敏感的。当然开发人员可以显式指定大小写敏感。

Entries Recognizer

对于一组已知词汇,开发人员可以通过如下方式创建识别器。

var bot = new OscovaBot();
bot.CreateRecognizer("employee", new[] { "Sean", "Ali", "Patel" });

另一种写法,但意思完全一样

var recognizer = bot.CreateRecognizer("employee");
recognizer.Entries.Add("Sean");
recognizer.Entries.Add("Ali");
recognizer.Entries.Add("Patel");

大小写敏感的识别器。

var bot = new OscovaBot();
bot.CreateRecognizer("employee", new[] { "Sean", "Ahmet", "Patel" }, StringComparer.Ordinal);

Enumeration Recognizer

用于枚举类型的识别器:

enum PriorityTypes
{
    Low,
    High,
    Mininum,
    Maxinum
}

然后,

var bot = new OscovaBot();
bot.CreateRecognizer<PriorityTypes>("priority");

明白了吧!当然大小写不敏感的:

var bot = new OscovaBot();
bot.CreateRecognizer<PriorityTypes>("priority", StringComparer.Ordinal);

还可以指定同义词:

enum PriorityTypes
{
    Low,
    High,

    [Synonyms("Min")]
    Minimum,

    [Synonyms("Max")] Maximum }

在读取的时候将实体类型转换到对应的枚举上。
var entity = result.Entities.OfType("priority");
var priority = entity.ValueAs<PriorityTypes>();
 

Pattern Recognizer

模式识别器就是用正则表达式来做识别。

var regex = new Regex("[0-9a-fA-F]+[\r\n]*");
bot.CreateRecognizer("hex", regex);

Functional Recognizer

函数类型的识别器,就是指定一个函数来处理用户输入,解析出实体对象。

如果要用于处理数据库对象,而不是将所有实体加载到内存,这种方法创建识别器非常方便。

bot.CreateRecognizer("name", request =>
{
    var entities = new EntityCollection();
    var message = request.NormalizedText;
    foreach (var item in SomeValues) { var index = message.IndexOf(item, StringComparison.OrdinalIgnoreCase); if (index == -1) continue; var entity = new Entity("name") { Value = item, Index = index }; entities.Add(entity); } return entities; });

Custom Recognizer

自定义的识别器,实现Syn.Bot.Oscova.Interfaces.IEntityRecognizer 即可。

比如自定义了一个html实体对象,

public class HtmlEntity : IEntity
{
    public HtmlEntity() { Type = "html"; } public string Type { get; set; } public string Value { get; set; } public int Index { get; set; } }

然后实现接口

public class HtmlRecognizer : IEntityRecognizer
{
    public string Type => "html"; public EntityCollection Parse(Request request) { var regex = new Regex(@"<(?<tag>\w*)>(?<text>.*)</\k<tag>>"); var entities = new EntityCollection(); foreach (Match match in regex.Matches(request.NormalizedText)) { var entity = new HtmlEntity { Value = match.Value, Index = match.Index }; entities.Add(entity); } return entities; } }

需要注意的是,所有实体必须指定索引参数Index,它标记了用户输入中内容匹配的顺序。

自定义完成记得添加到bot.Recognizers 集合中,这个操作应该在训练之前。

猜你喜欢

转载自www.cnblogs.com/mrtiny/p/9082819.html