Last active
January 6, 2017 15:24
-
-
Save lunaluxie/28009999afea413933836cddf5b8e1a1 to your computer and use it in GitHub Desktop.
Weighted random sentence constructor from dictionary words and weights
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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