Return a random word from a word list in python
python
Solution
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.
Problem
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))], ```