我希望用户输入一个句子,然后在该句子中随机选择一个单词并打印出来。我不知道怎么做,有什么帮助吗? 到目前为止,我只能从句子中选择一个字母。
答案 0 :(得分:0)
你基本上需要做的是: 提示输入,分成单个单词,然后在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
答案 1 :(得分:0)
这可以满足您的要求,就像上面的答案一样,但是如果您愿意,可以使用此功能。
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)))]
答案 2 :(得分:0)
#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)