lundi 14 novembre 2016

Python: Replacing multiple words with a random choice

I have a phrase with some special marked words which I want to replace. These words match a key in a dictionary, which has a list of words that I want to randomly choose to replace with.

I'm wondering if there's a better way to go about doing this, or is what I have seem like a valid approach? I have a feeling there may be a smarter way with lambda but I'm not sure.

Hopefully the code explains for itself!

import random

words = {"fruit":["apples", "bananas", "oranges"], 
         "veggies":["broccoli", "corn", "cucumbers"]}

txt = "I'm not in a mood for [veggies], I rather have [fruit]."

for key in words:
    target_word = "[{0}]".format(key)

    while target_word in txt:
        txt = txt.replace(target_word, random.choice(words[key]), 1)

Running it a few times will randomly output:

I'm not in a mood for corn, I rather have bananas.

I'm not in a mood for broccoli, I rather have oranges.

I'm not in a mood for cucumbers, I rather have apples.

..and so on..




Aucun commentaire:

Enregistrer un commentaire