Skip to content

Instantly share code, notes, and snippets.

@lunaluxie
Last active January 6, 2017 15:24
Show Gist options
  • Save lunaluxie/28009999afea413933836cddf5b8e1a1 to your computer and use it in GitHub Desktop.
Save lunaluxie/28009999afea413933836cddf5b8e1a1 to your computer and use it in GitHub Desktop.
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:
keys.append(key)
values.append(dict_weighted[key])
# 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