使用Python生成句子
我想用Python生成句子。我已经有了需要的单词,但不知道怎么才能让运行后只输出正确的句子。
这是我的代码:
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 个回答
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
1
大约六个月前,我想起了一个老程序叫做 racter,于是我用Python做了一个类似的版本。这个程序可能更像是MadLibs游戏,而不是生成真正的句子。我把它做成了一个在线工具,放在了Utility Mill网站上:http://utilitymill.com/utility/Graduation_speech