コード例 #1
0
def main():
    # Create a grammar and add some rules to it
    grammar = RootGrammar()
    name = HiddenRule("name", AlternativeSet("john", "bob", "anna"))

    # greeting is either: 'hey', 'hey there' or 'hello'
    greeting = HiddenRule("greeting", AlternativeSet(
        Sequence("hey", OptionalGrouping("there")), "hello"))

    # parting_phrase is either: 'good bye' or 'see you'
    parting_phrase = HiddenRule("parting_phrase", AlternativeSet(
        "good bye", "see you"))

    # greet is a greeting followed by a name
    greet = PublicRule("greet", Sequence(RuleRef(greeting), RuleRef(name)))

    # goodbye is a parting phrase followed by a name
    goodbye = PublicRule("goodbye", Sequence(
        RuleRef(parting_phrase), RuleRef(name)))

    grammar.add_rules(name, greeting, parting_phrase, greet, goodbye)

    print("Root grammar compiles to the following:")
    print(grammar.compile())

    # Try matching some speech strings
    print_matching(grammar, "hey john")
    print_matching(grammar, "hey there john")
    print_matching(grammar, "see you john")

    # Try matching some hidden rules
    print_matching(grammar, "bob")
    print_matching(grammar, "hey there")
    print_matching(grammar, "good bye")
コード例 #2
0
def create_grammar(word_list, name, gram_file):
    """
    read a list in a text file (```word_list````) and create
    a grammar (```name```) file (```gram_file```) for that list,
    such that the speech can one of any of the elements of the list
    """
    upp_list = list()
    grammar = RootGrammar(name=name, case_sensitive=True)
    i = 0
    for lines in word_list:
        rule_name = "rule" + str(i)
        upp = lines.upper().strip()
        #print("upp is",upp)
        if upp != "" and upp != "{" and upp != "}" and upp != "." and upp[
                0] != "_":
            r = PublicRule(rule_name, upp, case_sensitive=True)
            grammar.add_rule(r)
            upp_list.append(upp)
            i = i + 1

    with open(gram_file, 'wt') as g:
        print(grammar.compile(), file=g)