-1

I need to generate sentences using python. I have the words I need intact but can't figure out how to make it so only correct sentences come out after I run it.

Here's my code

import random

def S():
    print DP(), VP()

def DP():
    detPhrase = D() + ' ' + N()
    return detPhrase

def VP():
    randInt = random.randint(0,1)
    if randInt == 0:
        return V() 
    else:
        return V() + ' ' + DP()

def N():
    nouns = ['cat', 'dog', 'Bella']
    randInt = random.randint(0,len(nouns)-1)
    return nouns[randInt]

def D():
    articles = ['the', 'to']
    randInt = random.randint(0,len(articles)-1)
    return articles[randInt]

def V():
    verbs = ['ran','kissed','gave']
    randInt = random.randint(0,len(verbs)-1)
    return verbs[randInt]

for num in range(30):
    S()
4

4 回答 4

2

阅读有关乔姆斯基层次结构的信息:http ://en.wikipedia.org/wiki/Chomsky_hierarchy#Formal_grammars

于 2013-02-10T23:32:53.930 回答
1

你可以通过正确识别词性来做出很大的改进:“to”是介词,而不是冠词

articles = ['the', 'a']

这不是莎士比亚,但至少我们在球场上:

a dog kissed the dog
a dog kissed the dog
the cat kissed
a cat kissed
a cat gave the dog
a dog kissed the cat
the dog gave
a dog kissed the dog
于 2013-06-29T20:47:28.437 回答
1

大约 6 个月前,我想起了旧的racter程序,并拼凑了一个 Python 变体。它可能比实际的句子生成更接近 MadLib。我将它打包为 Utility Mill 的在线实用程序:http: //utilitymill.com/utility/Graduation_speech

于 2013-02-10T23:42:45.263 回答
0

在圣诞节假期里,我写了hornet,它是 Python 3.3 中类似 Prolog 的嵌入式 DSL。它还不是很好 - 只是一个概念证明 - 并且没有文档可言,但有一个文件parsing.py包含简单德语句子的 DCG 规则。您可以尝试一下并查看代码。也许它对你有一些帮助。

于 2013-02-11T00:38:22.373 回答