Crate genex[−][src]
Expand description
Rust library implementing a custom text generation/templating system. Genex is similar to Tracery, but with some extra functionality around using external data.
Usage
First create a grammar, then generate an expansion or multiple expansions from it.
use std::collections::HashSet;
use std::str::FromStr;
use maplit::hashmap;
use genex::Grammar;
let grammar = Grammar::from_str(
r#"
RULES:
top = <identifier> <action>
identifier = [The #occupation#|#name#]
action = [ran|ate|sat|slept|examined the #patient#]
WEIGHTS:
name = 2
occupation = 1
"#,
)
.unwrap();
let data = hashmap! {
"name".to_string() => "Sam".to_string(),
"patient".to_string() => "lizard".to_string(),
};
// Find the top-scoring expansion (the one that uses the most external
// variables):
let best_expansion = grammar.generate("top", &data).unwrap().unwrap();
assert_eq!(
best_expansion,
"Sam examined the lizard".to_string()
);
// Get all possible expansions:
let all_expansions = grammar.generate_all("top", &data).unwrap();
assert_eq!(
HashSet::<_>::from_iter(all_expansions),
HashSet::<_>::from_iter(vec![
"Sam ran".to_string(),
"Sam ate".to_string(),
"Sam sat".to_string(),
"Sam slept".to_string(),
"Sam examined the lizard".to_string(),
])
);Re-exports
pub use crate::error::Error;