简体   繁体   中英

Python Search and replace string by key and randomly select with multiple values

I'm a newbie and I need advice. How do I replace part text with other randomly selected text.

Sentence: Going to The Cinema. This should result in:

Going to work. OR Going to Car. OR Going to Restaurant.

A dictionary in a file might look something like this:

{“to The Cinema”: {“to Restaurant”, ”to work”, “to Car”}}

I now have a code that will replace word for word, and I don't know how to make a random selection when the slovník would be in the pattern above.

story = "Going to The Cinema."

file = open("my_dict.txt", "r", encoding="utf-8") # ex.:{"to The Cinema": "to Car"}
replace_all = file.read()
my_dict = ast.literal_eval(replace_all)
file.close()

def replace_all(text, dic):
    for i, j in dic.items():
        text = re.sub(r"\b%s\b"%i, j, text)
    return text

story = replace_all(story,my_dict)

print(story)

If I get it correctly you want to replace words in the string, named story, based on the dictionary, named my_dict. The keys are the words to search and replace with random values from the set.

import random


story = "Going to The Cinema."
my_dict = {"to The Cinema": ["to Restaurant", "to work", "to Car"]}  # <--

def replace_all(text, dic):
    for key, list_of_values in dic.items():
        while text.find(key) != -1:
            text = text.replace(key, random.choice(list_of_values), 1) # if you are planning to use sets use here: list(list_of_values)
    return text

story = replace_all(story, my_dict)

print(story)

I replaced the set with a list, because it seemed better for me (can not use random.choice on a set), indicated with the first comment. You can keep the set, if you follow the guidance in the second comment..

Little help, if you don't know the difference between sets, lists and dictionaries:

  • set: {a, b, c, d}
  • list: [a, b, c, d, d]
  • dict: {a:1, b:2, c:4}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM