Wolfram Language

Text & Language Processing

Define Grammar Rules

Build your own natural-language processing interface, combining the powerful built-in grammar tokens and rules of the Interpreter framework with your own custom grammar tokens and rules. Then deploy the interface to the Wolfram Cloud for further use in functions like GrammarApply.

Use the built-in "City" interpreter type to construct a parser for a list of city names with different delimiters and deploy it to the cloud.

In[1]:=
Click for copyable input
citiesGrammar = CloudDeploy[ GrammarRules[{ cs : DelimitedSequence[GrammarToken["City"], "," | ";" | "and"] :> cs }] ]
Out[1]=

Apply the parser to a string containing several cities in the US, returning a list of respective Entity objects.

In[2]:=
Click for copyable input
GrammarApply[citiesGrammar, "Saint Louis; New York, LA and Dallas"]
Out[2]=

They can now be processed by the Wolfram Geo functionality.

In[3]:=
Click for copyable input
GrammarApply[citiesGrammar, "Saint Louis; New York, LA and Dallas"]; GeoListPlot[%, GeoLabels -> Automatic, GeoBackground -> "CountryBorders", GeoRange -> "Country"]
Out[3]=

Add your own custom grammar tokens "Route", "Origin", and "Destination" and define rules for them.

In[4]:=
Click for copyable input
routeGrammar = CloudDeploy[ GrammarRules[{GrammarToken["Route"], GrammarToken["Origin"], GrammarToken["Destination"]}, { "Route" -> AnyOrder[start : GrammarToken["Origin"], end : GrammarToken["Destination"]] :> (start -> end), "Origin" -> FixedOrder["from", loc : GrammarToken["City"]] :> loc, "Destination" -> FixedOrder["to", loc : GrammarToken["City"]] :> loc } ] ]
Out[4]=

The combined use of AnyOrder and FixedOrder allows correct parsing of origin and destination in both orders.

In[5]:=
Click for copyable input
GrammarApply[routeGrammar, "from NYC to LA"]
Out[5]=
In[6]:=
Click for copyable input
GrammarApply[routeGrammar, "to LA from NYC"]
Out[6]=

Related Examples

de es fr ja ko pt-br ru zh