pytracery

repository·master·Indexed 42 days ago

https://github.com/aparrish/pytracery

A Python port of Kate Compton's Tracery, a tool for creating generative text through recursive grammar expansion. It allows developers to define rules and modifiers to produce randomized, structured text output via a Python API or a command-line interface using JSON grammar files.

Tokens
468
Snippets
4
Records
4
Agent score
4%

What's inside pytracery

  1. Use tracery to generate text from rules

    master

    To use tracery in Python, define your grammar rules using a Python dictionary. You then initialize a tracery.Grammar object with these rules. You can also add modifiers (like base_english) to enable transformations like capitalization. Use grammar.flatten() with a rule name enclosed in # symbols (e.g., "#origin#") to generate the expanded text.

    import tracery
    from tracery.modifiers import base_english
    
    rules = {
        'origin': '#hello.capitalize#, #location#!',
        'hello': ['hello', 'greetings', 'howdy', 'hey'],
        'location': ['world', 'solar system', 'galaxy', 'universe']
    }
    
    grammar = tracery.Grammar(rules)
    grammar.add_modifiers(base_english)
    print(grammar.flatten("#origin#"))  # prints, e.g., "Hello, world!"
  2. Generate text from a JSON grammar file via CLI

    master

    You can run the tracery module from the command line to generate text from a JSON Tracery grammar file.

    Arguments:

    • json: The input JSON file containing the grammar.
    • number (optional): The number of lines to generate. Defaults to 1.

    Examples:

    Generate one line:

    python -m tracery potterpapers.json

    Generate three lines:

    python -m tracery potterpapers.json 3