I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist.
import fileinput
import _random
file = [line for line in fileinput.input("/etc/dictionaries-common/words")]
rand = _random.Random()
print file[int(rand.random() * len(file))],
In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method.
This is a simple python package to generate random English words.
The random module defines choice(), which does what you want:
import random
words = [line.strip() for line in open('/etc/dictionaries-common/words')]
print(random.choice(words))
Note also that this assumes that each word is by itself on a line in the file. If the file is very big, or if you perform this operation frequently, you may find that constantly rereading the file impacts your application's performance negatively.
Another solution is to use getline
import linecache
import random
line_number = random.randint(0, total_num_lines)
linecache.getline('/etc/dictionaries-common/words', line_number)
From the documentation:
The linecache module allows one to get any line from any file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file
EDIT: You can calculate the total number once and store it, since the dictionary file is unlikely to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With