随机生成句子的程序和 Emacs 排名的降低
#!/usr/bin/env python import random
END = "end" TITLE = -1
Noun = ["bug", "book", "piece of shit", "man", "iPod", "ass", "fool"] Be = ["is"] Vi = ["sucks", "rocks", "runs", "flies", "pisses"] Vt = ["eats", "reads", "laughs at", "bites", "kicks"] Adj = ["red", "passing", "shitty", "dying", "silly"] Adv = ["finally", "reluctantly", "happily", "unwillingly"] Trans = ["that", "which"] Artical = ["the", "a"]
MainPart = {TITLE: "Main part", 1: [(Adv, 4), (Be, 3)], 2: [(2, END)], 3: [(Adj, END)], 4: [(Vi, END), (Vt, 2)]} NounClause = {TITLE: "Noun clause", 1: [(Artical, 2)], 2: [(Noun, 3), (Adj, 2)], 3:[(Trans, 4)], 4: [(MainPart, END)]} Subject = {TITLE: "Subject", 1: [(Artical, 2), (NounClause, END)], 2: [(Noun, END)]} Object = Subject Sentence = {TITLE: "Sentence", 1: [(Subject, 2)], 2:[(MainPart, END)]} EleList = [Sentence, Subject, Object, NounClause, MainPart]
def genSentence(tree): random.seed() Sent = "" Index = 1 if type(tree) == type({}): while Index != END: Node = random.choice(tree[Index]) After = genSentence(Node[0]) if After != None: Sent = ' '.join([Sent, After]) Index = Node[1] elif type(tree) == type(""): return tree elif type(tree) == type([]): return random.choice(tree) elif type(tree) == type(1): while Index != END: Node = random.choice(EleList[tree][Index]) After = genSentence(Node[0]) if After != None: Sent = ' '.join([Sent, After]) Index = Node[1] elif tree == None: return else: print "Error: invalid type of tree in genSentence()." return ' '.join(Sent.split())
def main(): print genSentence(Sentence).capitalize() + '.' return
if name == "main": main()