Parsing files that use synonyms

Tags: perl random unix
By : Lin

If I had a text file with the following:

    Today (is|will be) a (great|good|nice) day.

Is there a simple way I can generate a random output like:

    Today is a great day.
    Today will be a nice day.

Using Perl or UNIX utils?

By : Lin


Smells like a recursive algorithm

Edit: misread and thought you wanted all possibilities

import re, random

def expand(line, all):
    result ='\([^\)] \)', line)
    if result:
        variants =[1:-1].split("|")
        for v in variants:
            expand(line[:result.start()]   v   line[result.end():], all)
    return all

line = "Today (is|will be) a (great|good|nice) day."

all = expand(line, [])

# choose a random possibility at the end:
print random.choice(all)

A similar construct that produces a single random line:

def expand_rnd(line):
    result ='\([^\)] \)', line)
    if result:
        variants =[1:-1].split("|")
        choice = random.choice(variants)
        return expand_rnd(
                line[:result.start()]   choice   line[result.end():])
        return line

Will fail however on nested constructs

This video can help you solving your question :)
By: admin