Saturday, April 3, 2010

Writing a program similar to the unix 'fortune'

A simple program to read fortunes from "fortunes.txt" and print a random one to the screen.


import fileinput
import random

# loading the fortunes file as elements of a list;
# using fileinput we don't load the whole file in memory
fortunes = []
for line in fileinput.input(['fortunes.txt']):
if not line.strip() == '': # skip blank lines
fortunes.append(line)

# printing a random fortune:
print "\n" + fortunes[random.randint(0, len(fortunes)-1)]



The file "fortunes.txt" would have for instance the following contents (or e.g. these), separated by blank lines:


Never take life seriously. Nobody gets out alive anyway.

Behind every successful man is a surprised woman. - Maryon Pearson

Hard work never killed anybody, but why take a chance?

I am not a vegetarian because I love animals; I am a vegetarian because I hate plants. A. Whitney Brown

No comments:

Categories

code (15) fun (2) linux (31) miscellaneous (9) music (8)

About me

I'm Adrian and this is my blog. Here I usually write about technical stuff (mostly about Linux).
Copyright: BY-NC_SA, Author: aeter