Monday, September 22, 2008

Easy flashcards

My intention with this blog is to post small scripts I write just for fun, hoping that they will become useful to someone. I love cooking during the breaks when I am coding, this way I can eat during the compilation time or tests execution. With this in mind, I will also post some quick recipes that will help you to have a good time both coding and cooking.

Let's start with an easy Python script. I wrote it this summer while having a French course. I needed a simple flashcards program in order to learn the body parts, portable (to share it with my course mates) and easy to use and extend with other words lists.

I decided to write an short script able to read lists of pairs of words. The script would give the first word from any pair, and the user should guess the corresponding word in the other language.

The source files containing the lists of pairs of words are written in simple YAML, so they may look like plain text to someone who doesn't know what YAML means. I could have used actual plain text in the script, but I wanted to learn how to use the YAML libraries for Python.


The code looks like this:

#!/usr/bin/env python
# encoding: utf-8
"""
main.py
Created by Rafael Rodriguez Calvo on 2008-08-05.
Usage: >python main.py source.yaml [other_source.yaml]*
"""

import sys
from operator import add
import yaml

def merge_dicts(a,b):
for k in b.keys():
a[k] = b[k]
return a

def main(sources):
words = [yaml.load(open(source, "r")) for source in sources]
words = reduce(merge_dicts,words)
for i in words.keys():
print i
raw_input()
print words[i]
print "\n"

if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))


And this is the YAML source file for the body parts:

las caderas: les hanches
el culo: les fesses
la lengua: la langue
el mentón: le menton
los dientes: les dents
el pelo (cabeza): les cheveux
la cabeza: la tête
la mano: la main
el pecho: la poitrine
el vientre: le ventre
el codo: le coude
la pierna: la jambe
la rodilla: le genou
el pie: le pied
el tobillo: la cheville
el brazo: le bras
el muslo: la cuisse
la espinilla: le tibia
la pantorrilla: le mollet
el talón: le talon
la cara: le visage
la ceja: le sourcil
el ojo: l'oeil
la oreja: l'oreille
la nariz: le nez
el cuello: le cou
los hombros: les epaules


The load function of the yaml module parses the source YAML file and returns a dictionary with all the pairs of words in it. As there may be multiple source files, the auxiliar function merge_dicts combines all them in a single dictionary, and takes care automagically of all the repeated items that may contain the multiple sources. Moreover, the items will be unsorted due to the nature of the Python dictionaries.

No comments: