簡體   English   中英

我如何從輸入中隨機選擇一個單詞(python)

[英]how do i randomly select a word from an input (python)

我希望用戶輸入一個句子,然后在該句子中隨機選擇一個單詞並打印出來。 我不知道該怎么做,有幫助嗎? 到目前為止,我只能從句子中選擇一個字母。

您基本上需要做的是:提示輸入,切成單個單詞,然后在隨機庫的幫助下選擇一個隨機單詞:

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

就像上面的答案一樣,這可以完成您想要的事情,但是如果您願意,可以使用此功能。

import random
sentence = input("Your sentence: ")
words = sentence.split()
words = random.shuffle(words)
yourword = words[0] # or, for more spoiled variation use: 
#yourword = words[random.randint(range(len(words)))]
#in this code we took the input as a list to make it easier taking each word of the sentence alone  
import sys , random 
sentence=sys.argv[1:]
r=random.choice(sentence)
print(r) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM