简体   繁体   中英

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.

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

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. Then it uses random.choice to pick one of them. It's good.

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.

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