-8
我希望用户输入一个句子,然后随机选择该句子中的词汇并打印。我不知道该怎么做,有什么帮助? 目前为止,我只能从句子中选择一个字母。我如何随机选择从输入(蟒蛇)一词
我希望用户输入一个句子,然后随机选择该句子中的词汇并打印。我不知道该怎么做,有什么帮助? 目前为止,我只能从句子中选择一个字母。我如何随机选择从输入(蟒蛇)一词
你基本上需要做的是: 提示输入,分割成单个的词语,然后选择一个随机单词与random library的帮助:
import random
inp = input("Input: ") # prompt for input
# With an example:
# Input: This is a sentence
# produces the string inp="This is a sentence"
list_input = inp.split() # split up the sentence into a list of words
# In our example:
# list_input = ["This","is","a","sentence"]
print(random.choice(list_input)) # choose a random item from the list of words
# In our example the print statement would choose randomly one of the four words
你尝试过这么远吗?告诉我们你的代码。 – trotta
你能告诉我们你到目前为止所尝试过的吗? – Nuageux
'split'输入空格上创建列表,从列表中使用'从choice'选择一个随机元素'random' –