随机生成句子的程序和 Emacs 排名的降低

写了一个用来搞笑的 python 程序,可以随机地按照一定的语法生成句子。若干时间前写过一个功能差不多的程序,但是比较傻逼。

这个程序使用了 recursive transition networks 来表示一些简单的语法,目前可以递归地生成主语从句和宾语从句,并组合成完整的句子。看一些例子:

  • The fool which reluctantly rocks unwillingly eats a book.
  • The silly man that is silly unwillingly kicks a book which finally pisses.
  • A book reluctantly eats a bug that is red.
  • A man unwillingly sucks.
  • The piece of shit that happily runs reluctantly kicks a bug.

:-p 词表里本来还有一个 fucking 的,考虑到这里的都是文化人,删了。代码在最后。

另外,Vincent 在 The slow downfall of Emacs 里写道 Emacs 在编辑器中的 popularity 排名正在降低。在几年前,编辑器的 top two 永远是 Vi/Vim 和 Emacs,但是现在 Emacs 竟然落在了 GEdit 和 Kite 之后(这帮傻逼都是怎么想的?!),到底是为什么?Vincent 在最后写道:“Why is that? Not pretty enough? Too powerful for the simple needs of the new users that Ubuntu brought to the Linux world?”

#!/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()

comments powered by Disqus