You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects the lengths of a specified number of words from a given text. First, the text is split into a list of words, then the lengths of all words are extracted, and a random sample of the specified number of lengths is chosen.
Technology Stack : Python standard library (str.split(), list comprehension, random.sample)
Code Type : String processing
Code Difficulty : Intermediate
import random
def get_random_word_length(text, num_words=10):
words = text.split()
word_lengths = [len(word) for word in words if word.isalpha()]
random_lengths = random.sample(word_lengths, num_words)
return random_lengths