简体   繁体   English

我如何从 Python 2.7 中的 PyDictionary 模块中获取随机单词?

[英]How can i get a random word from the PyDictionary module in Python 2.7?

I want to use this for a word guessing game and I have tried to write a text file to do so.我想将它用于猜词游戏,并且我尝试编写一个文本文件来实现。 Is there a cleaner way?有没有更清洁的方法? Any help would be highly appreciated.任何帮助将不胜感激。

I've done a word guessing game before and the easiest way I found to generate a random word was to have a dictionary text file (I used /usr/share/dict/words ) that I read into a list and used the random standard library to generate a random number that was bounded by the length of our word list and use the random number to pick a word from the list. 我之前做过一个猜单词游戏,发现生成随机单词的最简单方法是拥有一个字典文本文件(我使用/usr/share/dict/words ),该文件被读入列表并使用random标准库生成一个随机数,该随机数受单词列表的长度限制,并使用该随机数从列表中选择一个单词。

import random
filename = "/usr/share/dict/words"
candidates = [x.strip().lower() for x in open(filename,"r")]
word = candidates[(random.randint(0,len(candidates) - 1))]

You can also use requests to download a words file (eg english-words ) if you don't have/don't want to use /usr/share/dict/words 如果您没有/不想使用/usr/share/dict/words也可以使用requests来下载单词文件(例如english-words

import requests
import random
def getRandomWord():
    word_url = 'https://itoven-ai.co/images/words.txt'
    r = requests.get(word_url, allow_redirects=True)
   #print(r.text.split("\n"))
    return random.choice(r.text.split("\n"))

Explanation: The words.txt file at this url I made available has a ton of words line by line, one word per line, so I get the text from this url and split by line.说明:我提供的这个 url 的 words.txt 文件逐行包含大量单词,每行一个单词,所以我从这个 url 获取文本并逐行拆分。 Then it uses random.choice to pick one of them.然后它使用 random.choice 来选择其中之一。 It's good.很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM