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")
If you're doing this repeatedly, I would download it locally and pull from the local file. *nix users can use /usr/share/dict/words
.
Example:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
If you want to pull from a remote dictionary, here are a couple of ways. The requests library makes this really easy (you'll have to pip install requests
):
import requests
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.content.splitlines()
Alternatively, you can use the built in urllib2.
import urllib2
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.
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()
Output:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:
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)])
And some random names:
>>> 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'
There is a package random_word could implement this request very conveniently:
$ 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()
网上有很多字典文件——如果你在 linux 上,很多(所有?)发行版都带有 /etc/dictionaries-common/words 文件,你可以轻松解析( words = open('/etc/dictionaries-common/words').readlines()
,例如)供使用。
from urllib.request import Request, urlopen
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
print(webpage)
Randomizing the first 500 words
from urllib.request import Request, urlopen
import random
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
first500 = webpage[:500].split("\n")
random.shuffle(first500)
print(first500)
Output
['abnegation', 'able', 'aborning', 'Abigail', 'Abidjan', 'ablaze', 'abolish', 'abbe', 'above', 'abort', 'aberrant', 'aboriginal', 'aborigine', 'Aberdeen', 'Abbott', 'Abernathy', 'aback', 'abate', 'abominate', 'AAA', 'abc', 'abed', 'abhorred', 'abolition', 'ablate', 'abbey', 'abbot', 'Abelson', 'ABA', 'Abner', 'abduct', 'aboard', 'Abo', 'abalone', 'a', 'abhorrent', 'Abelian', 'aardvark', 'Aarhus', 'Abe', 'abjure', 'abeyance', 'Abel', 'abetting', 'abash', 'AAAS', 'abdicate', 'abbreviate', 'abnormal', 'abject', 'abacus', 'abide', 'abominable', 'abode', 'abandon', 'abase', 'Ababa', 'abdominal', 'abet', 'abbas', 'aberrate', 'abdomen', 'abetted', 'abound', 'Aaron', 'abhor', 'ablution', 'abeyant', 'about']
import random
import string
letters = string.ascii_letters
x = "".join(random.sample(letters,5))
print(x)
Above, letters
will contain all ASCII letter characters (lowercase & uppercase) like so:
>>> print(letters)
>>> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Using random.sample
will provide you with a list of the total number of items (characters in this case) from the given object (a string
object here) based on the number you want ( random.sample(<string>, <# of random parts>
).
>>> random.sample(letters, 5)
>>> ['j', 'e', 'u', 'g', 'k']
Finally,
x = "".join(...)
will join together the returned list with no spaces because of "".
which can be changed to " ".
if you want spaces in between each letter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.