所以我基本上是在做一个项目,在这个项目中,计算机从一个单词列表中提取一个单词,然后为用户把它弄乱。只有一个问题:我不想一直在列表中写大量的单词,所以我想知道是否有一种方法可以导入大量的随机单词,这样即使我不知道它是什么,然后我也可以享受游戏?这是整个程序的代码,它只有6个单词,我把它放进去:
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")发布于 2013-09-17 03:07:47
读取本地单词列表
如果您重复这样做,我会将其下载到本地并从本地文件中提取。*nix用户可以使用/usr/share/dict/words。
示例:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()从远程字典中提取
如果你想从远程字典中提取数据,这里有几种方法。requests库使这一点变得非常简单(您必须使用pip install requests):
import requests
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.content.splitlines()或者,您可以使用内置的urllib2。
import urllib2
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()发布于 2018-03-28 09:36:49
Python 3的解决方案
对于Python3,下面的代码从web获取单词列表并返回一个列表。答案基于凯尔·凯利的accepted answer above。
import urllib.request
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()输出:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]并生成(因为这是我的目标)一个列表,其中包括1)仅大写的单词,2)仅“名字相似”的单词,以及3)某种真实但听起来有趣的随机名称:
import random
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
rand_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])和一些随机的名字:
>>> for n in range(10):
' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
'Semiramis Sicilian'
'Julius Genevieve'
'Rwanda Cohn'
'Quito Sutherland'
'Eocene Wheller'
'Olav Jove'
'Weldon Pappas'
'Vienna Leyden'
'Io Dave'
'Schwartz Stromberg'发布于 2019-07-01 15:33:06
有一个包random_word可以非常方便地实现这个请求:
$ pip install random-word
from random_word import RandomWords
r = RandomWords()
# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()https://stackoverflow.com/questions/18834636
复制相似问题