analitics

Pages

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
Crabapple
Hawthorn
Pear
Apricot
""".strip().split("\n")
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

Friday, September 11, 2009

How to use "try" ... "except"

Any program will be given over to error checking.
Python provides an exception handling capability.
There are two parts : "error checking" "catching exceptions".
Now let's try a simple example:

>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string 12
>>> try :
... input_str = int(input ("string "))
... except StandardError :
... print " This is not a number"
...
string aaa
This is not a number

The code :
input_str = int(input ("string "))

The code readed input will be convert in integer .
If types a value that's not an integer, the exception is caught.
In this case will print " This is not a number ".
This is very important because it generates more errors while running a program.
So, simply try to perform you action, and define what's to be done.
On except block if the action you want can't be completed.