[英]how do i randomly select a word from an input (python)
I want the user to input a sentence, then randomly select a word in that sentence and print it. 我希望用户输入一个句子,然后在该句子中随机选择一个单词并打印出来。 I do not know how to do this, any help? 我不知道该怎么做,有帮助吗? I can only select one letter from the sentence so far. 到目前为止,我只能从句子中选择一个字母。
What you basically need to do is: prompt for input, split into single words and then choose a random word with the help of the 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
This does the thing you want, just like the answer above, but if you wish you can use this one. 就像上面的答案一样,这可以完成您想要的事情,但是如果您愿意,可以使用此功能。
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.