Compartilhar via


Add Semantics to a GrammarBuilder Grammar

The SemanticResultValue and SemanticResultKey classes can be used to create grammars that process semantic values or meaning from an input phrase.

The grammar in the following example recognizes the English (U.S.) numbers "zero" through "nine" and returns the numeric values. If an application user says "three", this grammar returns the semantic value 3. Each call to Add([]) implicitly converts temp to a GrammarBuilder instance.

Choices digits = new Choices();
GrammarBuilder digitValues = new GrammarBuilder();

SemanticResultValue temp = new SemanticResultValue("zero", 0);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("one", 1);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("two", 2);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("three", 3);
digits.Add(temp);
digitValues.Append(temp);

// Code omitted follows a predictable pattern.

temp = new SemanticResultValue("eight", 8);
digits.Add(temp);
digitValues.Append(temp);

temp = new SemanticResultValue("nine", 9);
digits.Add(temp);
digitValues.Append(temp);

In the preceding example, each call to the SemanticResultValue(String, Object) constructor pairs a potential input word with its semantic value.

A SemanticResultKey instance can be used to access a semantic value established by a SemanticResultValue instance. Creating a SemanticResultKey establishes a pairing between a key name and an array of GrammarBuilder instances or strings. The grammar in the following example creates a grammar that combines the GrammarBuilder instance from the previous example with two SemanticResultKey instances, "first_value" and "second_value". The goal of this grammar is to recognize phrases such as "four plus nine equals" and to return the semantic values of the numbers in this phrase. For more information, see Use a SemanticResultKey to Extract a SemanticResultValue.

GrammarBuilder gb = new GrammarBuilder();
gb.Append(new SemanticResultKey("first_value", digits));
gb.Append("plus");
gb.Append(new SemanticResultKey("second_value", digits));
gb.Append("equals");
Grammar g = new Grammar(gb);
sr.LoadGrammar(g);

See Also

Concepts

Create Grammars Using GrammarBuilder