随机词生成器-Python

所以我基本上是在一个项目中,计算机从单词列表中提取一个单词,然后为用户弄乱它。只有一个问题:我不想一直在列表中写很多单词,所以我想知道是否有一种方法可以导入很多随机单词,所以即使我也不知道它是什么,并且那我也可以玩游戏吗?这是整个程序的编码,我只输入了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")

回答:

阅读当地单词列表

如果您重复执行此操作,我将在本地下载它并从本地文件中提取。* nix用户可以使用/usr/share/dict/words

例:

word_file = "/usr/share/dict/words"

WORDS = open(word_file).read().splitlines()

从远程字典中提取

如果您想从远程词典中提取信息,可以采用以下两种方法。请求库使这变得非常容易(您必须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()

以上是 随机词生成器-Python 的全部内容, 来源链接: utcz.com/qa/436501.html

回到顶部