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.
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):
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()
Answer from Kyle Kelley on Stack OverflowReading 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.
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):
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()
Solution for Python 3
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'
python - Generating random words - Stack Overflow
Generate random word of specific length
Created a random word generator program, looking for criticism
[deleted by user]
Continuing where you left off yesterday. Make sure to specify that you're working in Java in the future.
This is a good opportunity to practice a few different APIs. Like I said yesterday, look into using a BufferedReader for reading a file line by line. Let's work through it together.
try (BufferedReader reader = new BufferedReader(new FileReader("path/to/dictionary.txt")) {
// do stuff
} catch (IOException e) {
// handle exception
}
This is called a try-with-resources block. When working with anything that handles files, sockets, or the like you need to make sure that you let the system know you are done working with the file (or socket or whatever). A try-with-resources block gives you a scope level BufferedReader called reader that will be automatically closed at the end of the block. If an exception occurs the BufferedReader will still be closed. Before Java 7 introduced try-with-resources the pattern was similar to this:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("path/to/dictionary.txt"));
// do stuff
} catch (IOException e) {
// handle exception
} finally {
IOUtils.closeQuiety(reader); // often a static utility class to handle closing resources without rethrowing exceptions
}If you're using Java 7 or above use try-with-resources.
Let's look at the next bit: BufferedReader reader = new BufferedReader(new FileReader("path/to/dictionary.txt")) This is using the standard library's java.io classes. Something that trips up new Java programmers is that java.io makes heavy use of the Decorator pattern. What we're doing here is creating a BufferedReader that is wrapping a FileReader that is pointing to your dictionary text file. You could in theory use just a FileReader for this, but it would be really cumbersome. Wrapping it with a BufferedReader gives you a lot of convenience methods like BufferedReader.readerLine().
So now that we've gotten a BufferedReader we need to read in the file line by line. I'm assuming the dictionary file contains one word per line. Of course we need somewhere to store these lines. For that we'll use a List. If you haven't used a List before think of it as an array that can store an arbitrary amount of elements.
List<String> words = new ArrayList<>(); // create a new ArrayList that can old just Strings
try (BufferedReader reader = new BufferedReader(new FileReader("path/to/dictionary.txt")) {
String word;
while ((word = reader.readLine()) != null) {
words.add(word);
}
} catch (IOException e) {
// handle exception
}
We've now added a body to the try-with-resources that contains a while loop. The condition of the while loop might look kinda strange. (word = reader.readLine()) != null This is reading one line of the file and assigning it to word. It is then checking word to see if it is not null. If word is null that means we've hit the end of the file, as per the javadoc for BufferedReader.readLine(). So while we keep reading a line from the dictionary file we add those words one at a time to our List<String> words. Once we reach the end of the while loop we're done with the try-with-resources. The BufferedReader reader will be closed for us and your OS will be grateful that you're not keeping a handle on the dictionary file around.
Continued in next post.
More on reddit.comVideos
I want to generate a random word of a specific length. I found a python module called random-word and this is my code.
from random_word import RandomWords
r = RandomWords()
# Return a single random word
r.get_random_word()
result = None
while result is None:
try:
word1 = r.get_random_word()
print (word1)
if len(word1) == 5:
result = True
except:
print ('There was a problem')
# other code that uses result but is not involved in getting it
print (word1)
print (len(word1))It works perfectly fine, but it's very slow. It takes about 10 to 15 seconds to run until it finds a word of that length. Does anybody have a better way of doing this? Another way I thought was to maybe have a dictionary file and iterate through that. The reason I don't like that approach is I don't really like the idea of having to have a file on the machine. Also if it iterates through the file it won't be random.
Any suggestions appreciated.
Thanks
» pip install random_word
random.choice(words) * 5 executes random.choice only once and then multiplies the result by five, causing the same string to be repeated.
>>> import random
>>> words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
>>> print ''.join(random.choice(words) for _ in range(5))
applesomethinghellohellolalala
If you don't want the words from your original list to be repeated, then you could use sample.
import random as rn
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
word = ''.join(rn.sample(words, 5))
Result:
>>> word
'yeahhellosomethingapplenope'
» pip install Random-Word-Generator