Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a random word from a word list in python

Tags:

python

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))],
like image 446
kzh Avatar asked Sep 21 '09 20:09

kzh


People also ask

How do you randomly get an element from a list?

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.

Is there a Python module for random words?

This is a simple python package to generate random English words.


2 Answers

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.

like image 162
dcrosta Avatar answered Nov 15 '22 07:11

dcrosta


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.

like image 39
Nadia Alramli Avatar answered Nov 15 '22 07:11

Nadia Alramli