随机词生成器 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18834636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random word generator- Python
提问by Infamouslyuseless
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:
所以我基本上是在做一个项目,在这个项目中,计算机从一个单词列表中提取一个单词,然后为用户把它打乱。只有一个问题:我不想一直在列表中写大量的单词,所以我想知道是否有一种方法可以导入大量的随机单词,所以即使我也不知道它是什么,并且那我也能享受游戏吗?这是整个程序的编码,我输入的只有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")
采纳答案by Kyle Kelley
Reading a local word list
阅读本地单词表
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
.
如果您重复执行此操作,我会将其下载到本地并从本地文件中提取。*nix 用户可以使用/usr/share/dict/words
.
Example:
例子:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
Pulling from a remote dictionary
从远程字典中提取
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
):
如果你想从远程字典中提取,这里有几种方法。requests 库让这一切变得非常简单(你必须这样做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()
Alternatively, you can use the built in urllib2.
或者,您可以使用内置的 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()
回答by a p
There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines()
, eg) for use.
有许多在线词典文件 - 如果您使用的是 linux,很多(所有?)发行版都带有 /etc/dictionaries-common/words 文件,您可以轻松解析(words = open('/etc/dictionaries-common/words').readlines()
例如)以供使用。
回答by Giovanni G. PY
get the words online
在线获取单词
>>> words = requests.get("http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain").content.splitlines()
>>> x = 0
>>> for w in words:
... print(str(x) + str(w).replace("'b",""))
... x += 1
Output
输出
25477b'zooplankton'
25478b'Zorn'
25479b'Zoroaster'
25480b'Zoroastrian'
25481b'zounds'
25482b"z's"
25483b'zucchini'
25484b'Zulu'
25485b'Zurich'
25486b'zygote'
Store the names in local pc
将名称存储在本地电脑中
with open("dictionary.txt",'w') as file:
for w in words:
file.write(str(x) + str(w).replace("'b",""))
回答by amoodie
Solution for Python 3
Python 3 的解决方案
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer aboveby Kyle Kelley.
对于 Python3,以下代码从网络中获取单词列表并返回一个列表。答案基于凯尔·凯利 (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:
并生成(因为这是我的目标)一个列表,其中包含 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)])
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'
回答by Freman Zhang
There is a package random_wordcould implement this request very conveniently:
有一个包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()