简体   繁体   English

我如何从输入中随机选择一个单词(python)

[英]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.

相关问题 如何从 python 中的输入随机 select - How to randomly select from an input in python Python:如何从字典键中随机选择一个值? - Python: How do I randomly select a value from a dictionary key? 如何从列表中随机选择一个变量,然后在python中修改它? - How do I randomly select a variable from a list, and then modify it in python? 如何从列表中随机生成 python select 某些内容,如果在输入提示中键入,它将按预期显示确切答案 - How do I make python randomly select something from a list and if typed in the input prompt, it will show the exact answer as intended 我可以从列表中随机选择……但是如何将其用作不同命令的变量? 蟒蛇 - I can select randomly from a list… but how do I use this as a variable for different commands? Python 如何从列表中随机选择一个项目 - How do I randomly select an item from a list python:如何从总体中随机抽取多个样本? - python: how do I randomly sample a number of samples from a population? 如何从之前在 Python 中随机选择的列表中插入相同的单词? - How can I insert the same word from a list that was randomly chosen earlier in Python? 如何从用户输入的另一个变量中查找单词? - How do i find a word from user input in another variable? 我如何从列表中随机选择用户要求在 python 中使用输入的次数? - how do i randomly pick characters out of a list the amount of times the user asks for using input in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM