Parsing files that use synonyms

Tags: perl random unix
By : Lin
Source: Stackoverflow.com
Question!

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


Answers

Smells like a recursive algorithm

Edit: misread and thought you wanted all possibilities

#!/usr/bin/python
import re, random

def expand(line, all):
    result = re.search('\([^\)] \)', line)
    if result:
        variants = result.group(0)[1:-1].split("|")
        for v in variants:
            expand(line[:result.start()]   v   line[result.end():], all)
    else:
        all.append(line)
    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 = re.search('\([^\)] \)', line)
    if result:
        variants = result.group(0)[1:-1].split("|")
        choice = random.choice(variants)
        return expand_rnd(
                line[:result.start()]   choice   line[result.end():])
    else:
        return line

Will fail however on nested constructs



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