问题描述
因此,我基本上是在一个项目中,计算机从单词列表中提取一个单词,然后将其混杂给用户.只有一个问题:我不想一直在列表中写很多单词,所以我想知道是否有一种方法可以导入很多随机单词,所以即使我也不知道它是什么,并且那我也可以玩游戏吗?这是整个程序的编码,我只输入了6个字:
So i'm basically working on a project where the computer takes a word from a list of words and jumbles it up for the user. there's only one problem: I don't want to keep having to write tons of words in the list, so i'm wondering if there's a way to import a ton of random words so even I don't know what it is, and then I could enjoy the game too? This is the coding of the whole program, it only has 6 words that i put in:
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
word = random.choice(WORDS)
correct = word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print(
"""
Welcome to WORD JUMBLE!!!
Unscramble the leters to make a word.
(press the enter key at prompt to quit)
"""
)
print("The jumble is:", jumble)
guess = input("Your guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it")
guess = input("Your guess: ")
if guess == correct:
print("That's it, you guessed it!\n")
print("Thanks for playing")
input("\n\nPress the enter key to exit")
推荐答案
读取本地单词列表
如果您重复执行此操作,我将在本地下载并从本地文件中提取. * nix用户可以使用/usr/share/dict/words
.
示例:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
从远程词典中拉出
如果您想从远程词典中提取信息,可以采用以下几种方法.请求库使这变得非常容易(您必须pip install requests
):
import requests
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = requests.get(word_site)
WORDS = response.content.splitlines()
或者,您可以使用内置的urllib2.
Alternatively, you can use the built in urllib2.
import urllib2
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
这篇关于随机词生成器-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!