我想创建一个程序,通过创建10个从1到20的随机整数来生成随机短语,并且根据每个变量整数,将生成某个单词或短语。有没有比以下更简单的方法:
#This is a random phrase generator
import random
Rand1 = random.randint (1, 20)
Rand2 = random.randint (1, 20)
Rand3 = random.randint (1, 20)
Rand4 = random.randint (1, 20)
Rand5 = random.randint (1, 20)
Rand6 = random.randint (1, 20)
Rand7 = random.randint (1, 20)
Rand8 = random.randint (1, 20)
Rand9 = random.randint (1, 20)
Rand10 = random.randint (1, 20)
if Rand1 ==1:
print ('Squirrel')
等等...... P.S.使用Python 3
感谢您提供有用的建议。我是python的新手,让那些可以帮助我创建更好代码的人非常有帮助。如果有人关心,我用这个与你交谈的程序,并让你有机会听到笑话和玩几个游戏。祝你有愉快的一天。
PPS我最终选择了:
import random
words = 'squirrel orca ceiling crayon boot grocery jump' .split()
def getRandomWord(wordList):
# This function returns a random string from the passed list of strings.
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
potato = getRandomWord(words)
print (potato) # plus of course all the other words... this is just the base.
答案 0 :(得分:10)
不确定。使用Python列表和/或词典。如果您从一个组中选择:
words = ['Some', 'words', 'any', 'number', 'of', 'them']
choices = [random.choice(words) for _ in range(10)]
print(' '.join(choices))
如果没有,您可以使用嵌套列表:
words = [['Sam', 'Joe'], ['likes', 'hates'], ['apples', 'drugs', 'jogging']]
choices = [random.choice(group) for group in words]
print(' '.join(choices))
这可以扩展到每组中的任意数量的组和单词。
答案 1 :(得分:4)
有各种更简单的方法。想到的第一个是有一个短语列表,然后使用random.choice(这样你也不必担心添加新单词和调整。
示例:
import random
part1 = ("Cat","Dog","Squirrel")
part2 = ("jumps", "walks", "crawls")
part3 = ("under","over")
print (random.choice(part1) + " " + random.choice(part2))
(编辑使用(Python 3的打印)
您还可以使用列表列表来构建整个字符串...
words = (part1, part2, part3)
print (" ".join([random.choice(word) for word in words]))
答案 2 :(得分:0)
import random
Rand1 = random.randint (1, 4)
random1words = ['','Squirrel','Falcon','Pig']
print (random1words[Rand1])
几乎肯定会更好
答案 3 :(得分:0)
在这里,这最初是从我的图书代码(一种密码形式)实现(图书密码)中获取的 取自此处:arnold/book cipher with python
但是我在代码中做了一些改动,以使其适合您的描述。
BOOK="shakespeare.txt" # Your book/document .txt file containing words (maybe, articles from wikipedia, whatever,)
#the content from this file (in this case, shakespeare.txt); will be taken and used in the random-word/phrase progress.
def GetBookContent(BOOK):
ReadBook = open(BOOK, "r")# Open <BOOK>(shakespeare.txt in this case) in reading mode, into ReadBook
txtContent_splitted = ReadBook.read();# assign the contents(splitted!) from <BOOK> into -> txtContent_splitted
ReadBook.close()#Closing the book
Words=txtContent_splitted
return( txtContent_splitted.split() )
boktxt = GetBookContent(BOOK)
K
#Randomness happens here. We import random, assigns a range
#(in a form of a list!)
#from 0 to 10 into the variable K.
#and we shuffle K, (hence, we get the random word-indexes)
import random; K=list(range(0,10)); random.shuffle(K);
x=0;klist=K
for keys in klist: print(boktxt[int(klist[x])]);x=x+1
#Test Run:
#generating 10 random words.
# Before
# speak.
# me
# hear
# any
# what
# proceed
# further,
# First
# we