Python - Random Replacement of Word in String

Python - Random Replacement of Word in String

Creating a tutorial to write a Python program that randomly replaces a word in a string:

Objective: Given a sentence and a target word, replace the target word with another word randomly picked from a list of replacements.

Example:

Sentence: "The cat sat on the mat." Target word: "cat" Replacements: ["dog", "mouse", "bird"] Possible output: "The dog sat on the mat." 

Step-by-step Solution:

Step 1: Import necessary libraries.

import random 

Step 2: Define the input sentence, target word, and the list of possible replacements.

sentence = "The cat sat on the mat." target_word = "cat" replacements = ["dog", "mouse", "bird"] 

Step 3: Create a function to perform the random replacement.

def random_replace(sentence, target_word, replacements): # Pick a random replacement for the target word replacement = random.choice(replacements) # Replace the target word with the chosen replacement new_sentence = sentence.replace(target_word, replacement) return new_sentence 

Step 4: Call the function and display the modified sentence.

modified_sentence = random_replace(sentence, target_word, replacements) print(modified_sentence) 

Complete Program:

import random def random_replace(sentence, target_word, replacements): # Pick a random replacement for the target word replacement = random.choice(replacements) # Replace the target word with the chosen replacement new_sentence = sentence.replace(target_word, replacement) return new_sentence # Define the input data sentence = "The cat sat on the mat." target_word = "cat" replacements = ["dog", "mouse", "bird"] # Call the function and display the result modified_sentence = random_replace(sentence, target_word, replacements) print(modified_sentence) 

Possible Output:

The bird sat on the mat. 

Note: The output may differ each time you run the program because the replacement is selected randomly.

This tutorial provides a concise solution to randomly replace a target word in a sentence. Using Python's built-in string functions and the random.choice() method, you can easily modify text based on specific criteria.


More Tags

symfony2-easyadmin jasmine vbscript cluster-analysis parallax spring-rabbit asyncstorage imgur google-polyline asp.net-mvc-partialview

More Programming Guides

Other Guides

More Programming Examples