User Guide — fabulist 1.2.0 documentation

# User Guide

All random strings are generated by methods of the `Fabulist` class. Have a look at the `Reference Guide` for details.

## Some Examples

This code:

    from fabulist import Fabulist
    fab = Fabulist()

    # Print a random noun:
    print(fab.get_word("noun"):

    # Print a random adjective, tagged 'positive':
    print(fab.get_word("adj", "#positive"):

    # Print a random name, prefix with Mr./Mrs. and allow a middle-initial:
    print(fab.get_name("mr:middle"):

    # Print three random fragments, prefix with a/an:
    for s in fab.generate_quotes("Look, $(noun:an:#animal)!", 3):
        print(s)

will produce something like this:

    obligation
    kind
    Mrs. Julia P. Hughes
    Look, a tiger
    Look, an eagle!
    Look, a bug!

## More Examples

The following output was generated by this demo code:

    bash-3.2$ python -m tests.demo
    get_verb():
    -  counsel
    -  oblige
    -  discover
    Friendly warnings:
    -  Don't sell with my alarm or I'll nip your boxes.
    -  Don't stretch with my obligation or I'll pacify your guarantees.
    -  Don't sneak with my guide or I'll thump your deads.
    Software release names:
    -  detailed-bear
    -  unfortunate-rabbit
    -  weak-otter
    Compare:
    -  One gather may be far, but two gathers are farther.
    -  One exchange may be tidy, but two exchanges are tidier.
    -  One smile may be delayed, but two smiles are delayeder.
    Names:
    - My name is Mr. Isaac James
    - My name is Mr. Colin Powell
    - My name is Mr. Jacob K. Wilson
    Introduction:
    - Friends call me Harry, you can call me Mr. Harry A. May.
      May I introduce you to my wife Mrs. Rose May?
    - Friends call me Keith, you can call me Mr. Keith Taylor.
      May I introduce you to my wife Mrs. Madeleine Taylor?
    - Friends call me Dominic, you can call me Mr. Dominic W. Ross.
      May I introduce you to my wife Mrs. Lily Ross?
    Compliments:
    -  You have very reliable performances.
    -  You have very intelligent leagues.
    -  You have very good fingers.
    Blessings:
    -  May your scripts express joyfulliest.
    -  May your motors dip correctliest.
    -  May your wheels punish zestiliest.
    Fortune cookies:
    -  Confucius says: "The one who wants to inflate must greet coaxingly the communication!"
    -  Impressing is better than congratulating.
    -  Licking is better than scrawling.
    -  Existing is better than owing.
    -  Confucius says: "The one who wants to advise must smell smoothly the death!"
    Functions:
    -  Provide wilted digs
    -  Provide miniature minutes
    -  Provide loud visuals
    Potential failures:
    -  Shoulder restrains
    -  Definition does not welcome.
    -  Public develops
    Causes:
    -  Newspaper is too dear
    -  Subject is too powerful
    -  Loss is too firm
    bash-3.2$

## General Template Syntax

Templates are plain strings with embedded macros. Macros are formatted like `$(...)` and contain a word-type and optionally one or more modifiers, separated by colons (":"), for example
`$(noun)` or `$(noun:plural:#animal)`.

These macros can be embedded into template strings and will be replaced by random variations: `"Look at the beautiful $(noun:plural:#animal)!"`

### Supported Word Types

- `adj`: Adjective
  Word-form modifiers: `comp`, `super`, `antonym`.
  Tags: `#negative`, `#positive`
- `adv`: Adverb
  Word-form modifiers: `comp`, `super`, `antonym`.
  Tags: `#degree`, `#manner`, `#negative`, `#place`, `#positive`, `#time`
- `noun` Noun
  Word-form modifiers: `plural`
  Tags: `animal`
- `verb`: Verb
  Word-form modifiers: `ing`, `past`, `pp`, `s`
  Tags: -
- `@<num>`: Reference
  A special type to reference another macro in the template (see `:=<num>` modifier below)

NOTE: Use uppercase word-type name for capitalized results, e.g. `$(Noun)`.
NOTE: The `:antonym` modifier is not yet implemented.

Special Word Types:

- `name`: Generate person names
  See Modifiers for Names below.
- `num`: Generate random numbers
  See Modifiers for Numbers below.
- `pick`: Generate random value from a selection
  See Modifiers for Choices below.

## Modifiers

### Word Form Modifiers

By default, words are generated in their base form ('lemma'). At most one word-form modifier may be added to change this:

- `:comp` Comparative (adj, adv)
  $(adv) => "fast", $(adj:comp) => "faster"
- `:ing` (verbs only)
  $(verb) => "run", $(verb:ing) => "running"
- `:past` past form (verbs only)
  $(verb) => "arise", $(verb:past) => "arose"
- `:plural` (nouns only)
  $(noun) => "injury", $(noun:plural) => "injuries"
- `:pp` past perfect form (verbs only)
  $(verb) => "arise", $(verb:pp) => "arisen"
- `:s` -s/-es form (verbs only)
  $(verb) => "bash", $(verb:s) => "bashes"
- `:super` superlative (adj, adv)
  $(adj) => "big", $(adj:super) => "biggest"

### Additional Modifiers

These modifiers can used in addition to one word-form modifier:

- `:an`
  Prepend "a " or "an "
  $(noun) => "essay", $(noun:an) => "an essay"
- `:antonym`
  Adverbs and adjectives only: Use the opposite word. This is especially useful in combination with back-references:
  `"Don't be $(adj:=1). Be $(@1:antonym) instead!"`
  (NOTE: Not yet implemented!)
- `:#<tags>`
  Only allow results tagged with this category.
  Pass multiple tags separated by '|', e.g.:
  `$(noun:#animal)`, `$(adv:#manner|positive)`
  Note that first names are tagged with `#f` and/or `#m` for female/male:
  $(name:#m) => "John Doe"
- `:=<num>`
  Store result for back-reference using `@<num>`.
  `"One $(noun:=1) is good, but two $(@1:plural) are better."`

### Modifiers for Names

Names are produced by the `Fabulist.get_name()` method or using a `$(name)` macro.

These modifiers are available for names only:

- `:first` only use first name
  $(name) => "Diana Chapman", $(name:first) => "Diana"
- `:last` only use last name
  $(name) => "Diana Chapman", $(name:last) => "Chapman"
- `:middle` generate a middle initial
  $(name) => "Diana Chapman", $(name:middle) => "Diana S. Chapman"
- `:mr` prepend "Mr." or "Mrs."
  $(name) => "Diana Chapman", $(name:mr) => "Mrs. Diana Chapman"

NOTE: If neither `:first` nor `:last` is given, it is assumed that both parts are requested.

NOTE: Use `#m` or `#f` tags to restrict to male/female names:
$(name:#m) => "George Clarkson", $(name:first:#f) => Cindy

### Modifiers for Numbers

Random numbers within a given range are produced by the `Fabulist.get_number()` method or using a `$(num)` macro.

The `num` word type only accepts on modifier with a special syntax:

- `$(num:min,max,width)`, e.g.
  $(num:1,999,3) => "042"
- `$(num:min,max)`
  $(num:1,999) => "42"
- `$(num:max)`
  $(num:999) => "42"

### Modifiers for Choices

Random numbers within a given range are produced by the `Fabulist.get_choice()` method or using a `$(pick)` macro.

`$(pick:CHOICES)` where CHOICES may be a

- A comma separated list of strings:
  $(pick:foo,bar,baz) => "bar"
- A single string of characters
  $(pick:abc) => "c"

Special characters can be escaped by a backslash:
`$(pick:!#\,\:) => ","`

NOTE: It is recommended to use the raw string syntax (`r"..."`) to ensure that the backslash is always passed correctly:
`get_quote(r"$(pick:!#\:)")`

## Tips & Tricks

Mix fabulist macros with standard python formatting to insert random numbers for example:

    import random
    from fabulist import Fabulist

    fab = Fabulist()
    count = random.randint(2, 100)
    color = random.choice(["red", "green", "yellow"])
    template = "I need {count} {color} $(noun:plural).".format(count=count, color=color)
    res = fab.get_quote(template)

Load additional custom word list from a file or static list. Note that the data formats must match the word list type.

    fab = Fabulist()
    # Load stock lists
    fab.load()
    # Add entries from custom file
    fab.verb_list.load("my/verbs.txt")
    # Add entries dynamically
    data = [
      {"lemma": "The Beatles", "plural": False, "tags": ["band"]},
      {"lemma": "Rolling Stones", "plural": False, "tags": ["band"]},
      {"lemma": "foobar"},
      ]
    for d in data:
      fab.noun_list.add_entry(d)
    fab.update_data()

## Generate Blind Text

In addition to the above functionalities, Fabulist also features some methods to produce blind text, also known as Lorem Ipsum.

See the `Fabulist.get_lorem_*()` methods for details.

Some examples here:

    >>> fab.get_lorem_words(10)
    ['tation', 'placerat', 'officia', 'blandit', 'nisi', 'elit', 'eu', 'mazim', 'sadipscing', 'suscipit']

    >>> fab.get_lorem_sentence()
    Dolores takimata lorem nihil dignissim officia dolore voluptate nostrud commodo deserunt.

    >>> fab.get_lorem_paragraph(3, dialect="pulp", entropy=1)
    Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it? Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it?

    >>> fab.get_lorem_paragraph(3, dialect="trappatoni")
    Es gibt keine deutsche Mannschaft spielt offensiv und die Name offensiv wie Bayern. Ist klar diese Wörter, ist möglich verstehen, was ich hab gesagt? Danke. Offensiv, offensiv ist wie machen wir in Platz.

    >>> fab.get_lorem_paragraph(3, dialect="faust")
    Zerstoben ist das freundliche Gedränge, Er scheint mir, mit Verlaub von Ew. Gnaden, Mir geht es wie der Katze mit der Maus.

    >>> fab.get_lorem_paragraph(3, dialect="romeo")
    Would I were sleep and peace, so sweet to rest! That monthly changes in her circled orb, I shall forget, to have thee still stand there,

    >>> fab.get_lorem_text(3, keep_first=True)
    Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
    Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.
    Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua.