以下 Python 代码将生成具有给定终端数的随机句子。它的工作原理是计算产生给定长度的句子的方法数量,生成一个大的随机数,然后计算指示的句子。计数是递归完成的,带有记忆。如果 n 为 0,则空的右手边产生 1 个句子,否则产生 0 个句子。要计算由非空右手边产生的句子数量,请将 i 相加,即右手边第一个符号使用的终端数。对于每个 i,将右侧其余部分的可能性数量乘以第一个符号的可能性数量。如果第一个符号是终结符,则 i 为 1 的可能性为 1,否则为 0。如果第一个符号是非终结符,则对每个备选方案的可能性求和。为了避免无限循环,我们必须小心地在数量为 0 时修剪递归调用。如果语法有一个句子的无限多个推导,这仍然可能无限循环。例如,在语法
S -> S S
S ->
空句有无数个推导: S => 、 S => SS => 、 S => SS => SSS => 等。查找特定句子的代码是对代码进行计数的直接修改. 这段代码相当有效,在不到一秒的时间内生成了 100 个句子,每个句子有 100 个终端。
import collections
import random
class Grammar:
def __init__(self):
self.prods = collections.defaultdict(list)
self.numsent = {}
self.weight = {}
def prod(self, lhs, *rhs):
self.prods[lhs].append(rhs)
self.numsent.clear()
def countsent(self, rhs, n):
if n < 0:
return 0
elif not rhs:
return 1 if n == 0 else 0
args = (rhs, n)
if args not in self.numsent:
sym = rhs[0]
rest = rhs[1:]
total = 0
if sym in self.prods:
for i in xrange(1, n + 1):
numrest = self.countsent(rest, n - i)
if numrest > 0:
for rhs1 in self.prods[sym]:
total += self.countsent(rhs1, i) * numrest
else:
total += self.countsent(rest, n - self.weight.get(sym, 1))
self.numsent[args] = total
return self.numsent[args]
def getsent(self, rhs, n, j):
assert 0 <= j < self.countsent(rhs, n)
if not rhs:
return ()
sym = rhs[0]
rest = rhs[1:]
if sym in self.prods:
for i in xrange(1, n + 1):
numrest = self.countsent(rest, n - i)
if numrest > 0:
for rhs1 in self.prods[sym]:
dj = self.countsent(rhs1, i) * numrest
if dj > j:
j1, j2 = divmod(j, numrest)
return self.getsent(rhs1, i, j1) + self.getsent(rest, n - i, j2)
j -= dj
assert False
else:
return (sym,) + self.getsent(rest, n - self.weight.get(sym, 1), j)
def randsent(self, sym, n):
return self.getsent((sym,), n, random.randrange(self.countsent((sym,), n)))
if __name__ == '__main__':
g = Grammar()
g.prod('S', 'NP', 'VP')
g.prod('S', 'S', 'and', 'S')
g.prod('S', 'S', 'after', 'which', 'S')
g.prod('NP', 'the', 'N')
g.prod('NP', 'the', 'A', 'N')
g.prod('NP', 'the', 'A', 'A', 'N')
g.prod('VP', 'V', 'NP')
g.prod('N', 'dog')
g.prod('N', 'fish')
g.prod('N', 'bird')
g.prod('N', 'wizard')
g.prod('V', 'kicks')
g.prod('V', 'meets')
g.prod('V', 'marries')
g.prod('A', 'red')
g.prod('A', 'striped')
g.prod('A', 'spotted')
g.weight.update({'and': 0, 'after': 0, 'which': 0, 'the': 0})
for i in xrange(100):
print ' '.join(g.randsent('S', 3))