-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' –