Word Length Randomization in Text

  • Share this:

Code introduction


The function takes a string text and modifies the length of words within the string based on specified minimum and maximum lengths. If the length of a word is less than the minimum or greater than the maximum length, it replaces the word with a randomly generated one.


Technology Stack : random, string

Code Type : String processing

Code Difficulty : Intermediate


                
                    
def random_word_length(text, min_length=3, max_length=10):
    import random
    import string
    
    def generate_random_word(min_length, max_length):
        length = random.randint(min_length, max_length)
        return ''.join(random.choices(string.ascii_letters, k=length))
    
    words = text.split()
    modified_words = [generate_random_word(min_length, max_length) if len(word) < min_length or len(word) > max_length else word for word in words]
    return ' '.join(modified_words)                
              
Tags: