我想用双字母nltk生成十四行诗。我已经生成了二元组并计算了每个二元组的概率,并存储在这样的默认字典中。
[('"Let', defaultdict(<function <lambda>.<locals>.<lambda> at0x1a17f98bf8>,
{'the': 0.2857142857142857, 'dainty':
0.14285714285714285, 'it': 0.14285714285714285, 'those':
0.14285714285714285, 'me': 0.14285714285714285, 'us':
0.14285714285714285}))]
给出let之后出现的每个单词的概率。像这样,我的语料库有二元模型。现在,我想生成4行十四行诗,每行15个单词。我已经尝试过此代码,但是无法正常工作。
def generate_sonnet(word):
lines = 4
words= 15
for i in range(lines):
line = ()
for j in range(words):
#I am selecting max probability but not that word. How I can select that word which has max probability of occurring with word?
nword = float(max(model[word].values()))
word += nword
word = random.choice(poetrylist)
generate_sonnet(word)
我选择一个随机词并将其传递给我的函数。我想使用双字词连接15个单词,当一行完成时,接下来的3个单词应该完成。
我们将为您提供帮助
答案 0 :(得分:1)
下面是一个简单的代码段,显示了如何(非常幼稚的方法)完成此任务
bigram1 = {'Let' : {'the': 0.2857142857142857, 'dainty':
0.14285714285714285, 'it': 0.14285714285714285, 'those':
0.14285714285714285, 'me': 0.14285714285714285, 'us':
0.14285714285714285}}
bigram2 = {'the' : {'dogs' : 0.4, 'it' : 0.2, 'a' : 0.2, 'b': 0.2}}
bigram3 = {'dogs' : {'out' : 0.6, 'it' : 0.2, 'jj' : 0.2}}
model = {}
model.update(bigram1)
model.update(bigram2)
model.update(bigram3)
sentence = []
iterations = 3
word = 'Let'
sentence.append(word)
for _ in range(iterations):
max_value = 0
for k, v in model[word].iteritems():
if v >= max_value:
word = k
max_value = v
sentence.append(word)
print(" ".join(sentence))
输出
Let the dogs out
代码以非常简单的方式编写,这是理解建议的玩具示例
请记住,单词中遇到的第一个单词最大 值,因此该模型是确定性的,请考虑添加随机 从一组具有相同最大值的单词中进行选择的方法 值
我建议像这样按概率对单词进行采样
dist = {'the': 0.2857142857142857, 'dainty':
0.14285714285714285, 'it': 0.14285714285714285, 'those':
0.14285714285714285, 'me': 0.14285714285714285, 'us':
0.14285714285714285}
words = dist.keys()
probabilities = dist.values()
numpy.random.choice(words, p=probabilities)
这将根据给定的分布每次给您“随机”单词
smt这样(草稿)
for _ in range(iterations):
word = np.random.choice(model[word].keys(), p=model[word].values())