Thursday, September 17, 2009

Random words from lists and text

Sometimes it is necessary to choose random words from lists or texts.
Example below illustrates this:

import random
list_input = """ Apple
text_input = "This is a text without newline char".split()
print "List is =", list_input
print "---------------------------------------"
list_result = random.choice(list_input)
print "Random list result is =", list_result
print "---------------------------------------"
print "Text is =", text_input
print "---------------------------------------"
text_result = random.choice(text_input)
print "Random word result is =", text_result

We have two variables "list_input" and "text_input" containing a list of words separated by newline char and a simple string ending in newline char.
Its separation is made with function ".strip ()" .
This function separates the items in the list after this particular bracket expression. The result of the expression in brackets vanishes from the list.
The result of scripts is :

List is = ['Apple', ' Crabapple', ' Hawthorn', ' Pear', ' Apricot']
Random list result is = Pear
Text is = ['This', 'is', 'a', 'text', 'without', 'newline', 'char']
Random word result is = is