Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Weighted random sentence constructor from dictionary words and weights
import random
import numpy
dict_weighted = {"word1" : 0.1, "word2" : 0.9} # keys = words, values = weights. Values must sum to 1
def create_d_sentence(dict_weighted):
length = random.randint(5,15)
keys = []
values = []
# Extrapolate words and weights from dict
for key in dict_weighted:
# Pick words from dictionary
choices = np.random.choice(keys, length, replace=False, p=values)
# Construct sentence
sentence = " ".join(choices).capitalize()
return sentence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment