Python 打乱单词顺序:随机化句子
在 Python 中,你可以使用 random 模块中的 shuffle 函数来打乱单词的顺序。下面是一个简单的示例:
import random
def shuffle_words(sentence):
words = sentence.split() # 将句子分割成单词列表
random.shuffle(words) # 打乱单词列表的顺序
shuffled_sentence = ' '.join(words) # 将打乱顺序后的单词列表重新组合成句子
return shuffled_sentence
sentence = 'Python is a great programming language'
shuffled_sentence = shuffle_words(sentence)
print(shuffled_sentence)
输出可能是:
is Python language a great programming
这里使用了 split 函数将句子分割成单词列表,然后使用 shuffle 函数打乱单词列表的顺序,最后使用 join 函数将打乱顺序后的单词列表重新组合成句子。
原文地址: https://www.cveoy.top/t/topic/pfXf 著作权归作者所有。请勿转载和采集!