# CSE 143, Winter 2009, Marty Stepp # Homework 5 (Grammar Solver), in Python # # Instructor-provided testing program, by Marty Stepp # A client program that prompts a user for the name of a # grammar file and then gives the user the opportunity to generate random # versions of various elements of the grammar. from grammarsolver import * # Displays all non-terminal symbols, prompts for a symbol to generate, # and returns the symbol as a string. def get_symbol(solver): print("") print("Available symbols to generate are:") print(solver.symbols()) target = raw_input("What do you want to generate (Enter to quit)? ").strip() return target # Generates some number of instances of the given symbol. def do_generate(solver, symbol): number = int(raw_input("How many do you want me to generate? ")) if number >= 0: print("") for i in range(number): print(solver.generate(symbol)) else: print("No negatives allowed.") # main print("Welcome to the CSE 143 random sentence generator!") print("") # open grammar file; read its lines into a list filename = raw_input("What is the name of the grammar file? ") lines = [line.strip() for line in file(filename)] # construct grammar solver and begin user input loop solver = GrammarSolver(lines) # repeatedly prompt for symbols to generate, and generate them symbol = get_symbol(solver) while len(symbol) > 0: if solver.contains(symbol): do_generate(solver, symbol) else: print("Illegal symbol.") symbol = get_symbol(solver)