analitics

Pages

Tuesday, August 3, 2010

Random module - another example

Random module is a module used in everyday programming.
Even if it is not used in the final software, he helps us to test various types of random data.
We present you a simple example - play with cards.
We chose a list of cards of one color for not having a large number of elements.
We exemplify the use of random module by analogy with a game of cards.
That it means: shuffle cards , select just one from cards and a choice selection of a defined number of cards.
Below you see the code used as an example.

>>> import random
>>> choice=random.choice
>>> shuffle=random.shuffle
>>> for i in range (9):
...     print choice(cards)
... 
Q
K
10
Q
2
2
10
K
6
>>> shuffle(cards)
>>> cards
[4, 7, 10, 'J', 3, 'Q', 6, 2, 'K', 9, 'A', 8, 5]
>>> sample=random.sample
>>> sample(cards,5)
[8, 'J', 2, 'Q', 10]
>>> sample(cards,5)
['A', 9, 4, 'K', 'Q']
>>> 
The random module docs

Saturday, July 3, 2010

The module matplotlib-0.99.3

The module matplotlib is a python 2D plotting library with a variety of hardcopy formats and interactive environments across platforms.
With just a few lines of code we can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc...
See images bellow or visit the gallery.

This module is version 0.99.3 for Python 2.5 and 2.6. We have modules for installation on operating systems like MacOS, Windows and Linux.
To use this module you must have install numpy module.
Now download module from here.
$python setup.py build
Use super user:
#python setup.py install
Try to load module:
$python
Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) 
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> 
It's working fine.

Sunday, June 27, 2010

Add text on image with PIL module.

It's easy to create images with PIL module.
This is the script:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf",25)
img=Image.new("RGBA", (200,200),(120,20,20))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(255,255,0),font=font)
draw = ImageDraw.Draw(img)
draw = ImageDraw.Draw(img)
img.save("a_test.png")
The only error that can occur is not to find the font.
In this case you must change the code line:
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf",25)
Here is the result script:

Wednesday, June 2, 2010

The HTMLParser module - just simple example

Basically this module is for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
On HTMLParse docs.
You will see the same example but with no explanation. The example is :

import HTMLParser
from HTMLParser import *
import urllib2 
from urllib2 import urlopen

class webancors(HTMLParser):
 def __init__(self, url):
  HTMLParser.__init__(self)
  r = urlopen(url)
  self.feed(r.read())

 def handle_starttag(self, tag, attrs):
  if tag == 'a' and attrs:
   print "Link: %s" % attrs[0][1]
I named the python file : spiderweb.py
I use python to import this file:

>>> import spiderweb
>>> spiderweb.webancors('http://www.yahoo.com')
Link: y-mast-sprite y-mast-txt web
Link: y-mast-link images
Link: y-mast-link video
Link: y-mast-link local
Link: y-mast-link shopping
Link: y-mast-link more
Link: p_13838465-sa-drawer
Link: y-hdr-link

>>> 
The method handle_starttag takes two arguments from HTMLParser.
This arguments, tag and attrs is used to return values.
Note :
The HTMLParser module has been renamed to html.parser in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
Use "http://" not just "www". If don't use "http://" you see errors.
Seam urllib2 have some troubles with:

  File "/usr/lib/python2.5/urllib2.py", line 241, in get_type
    raise ValueError, "unknown url type: %s" % self.__original

You can use all functions HTTParser class.

Saturday, May 22, 2010

The beauty of Python: subprocess module - part 3

This is just a simple example about module subprocess.
We need to install "espeak" . On fedora usse this command:
#yum install espeak

Now the example is:

>>> import subprocess   
>>> subprocess.call(["espeak", "-s 120","-p 100","This is a test"])
0
>>>   

This will speak "This is a test".
This is all .

The beauty of Python: Some examples with os and sys modules - part 2

Today i will tell about sys and os modules.
The module os has OS routines for Mac, NT, or Posix depending on what system we're on.
The module sys provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter.

Some useful functions with sys module.
>>> print sys.version
2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2]
>>> print sys.version_info
(2, 5, 2, 'final', 0)
>>> print sys.subversion
('CPython', 'tags/r252', '60911')
>>> print sys.platform 
linux2
>>> print sys.ps1
>>> 
>>> print sys.ps2
... 
>>> print sys.prefix
/usr
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk',
'/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages',
 '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric',
'/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10',
 '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', 
'/var/lib/python-support/python2.5/gtk-2.0']
>>> print sys.modules.keys()
['apt.os', 'email.iterators', 'apport.sys', 'random', 'apport.atexit', 'subprocess',
 'email.MIMEImage', 'gc', 'apport.pwd', 'os.path', 'encodings.encodings', 'email.mime',
 'email.MIMEText', 'xml', 'email.time', 'struct', 'tempfile', 'base64', 'apt.cache',
 'pyexpat.errors', 'apt_pkg', 'apport', 'email.binascii', 'email.Parser', 'zipimport',
 'apport.xml', 'xml.dom.copy', 'encodings.utf_8', 'apt.apt_pkg', 'email.quoprimime',
 'email.mime.text', 'email.urllib', 'email.FeedParser', 'signal', 'email.encoders',
 'pyexpat.model', 'apport.packaging_impl', 'apport.cStringIO', 'quopri',
 'email.Message', 'cStringIO', 'zlib', 'locale', 'email.charset', 'apport.fileutils',
 'xml.parsers.expat', 'atexit', 'email.quopriMIME', 'encodings', 'email.Generator',
 'apport.warnings', 'apport.problem_report', 'apt.fcntl', 'email.MIMEAudio', 'urllib',
 're', 'apt.select', 'email.quopri', 'apport.report', 'email.mime.base', 'email.errors',
 'email', 'math', 'fcntl', 'apport.os', 'apt.progress', 'UserDict', 'exceptions',
 'apport.grp', 'apport.shutil', 'codecs', 'xml.dom.domreg', 'email.Header', '_locale',
 'email.Iterators', 'socket', 'thread', 'traceback', 'apt.apt', 'e,
 'SUDO_COMMAND': '/bin/su', 'SUDO_GID': '999', 'SDL_VIDEO_CENTERED': '1',
 'PWD': '/home/mint/Desktop', 'COLORTERM': 'gnome-terminal', 'MAIL': '/var/mail/root'}
mail.Charset', 'xml.dom.xmlbuilder', 'os', 'marshal', 'apport.stat', 'apport.re',
 'apt.gettext', 'email.uu', '_sre', 'unittest', '__builtin__', 'apport.apport',
 'xml.parsers', 'apport.fnmatch', 'apport.urllib', 'operator', 'xml.parsers.pyexpat',
 'email.Errors', 'select', 'apt.string', 'apport.glob', 'apt.warnings', 'email.socket',
 'posixpath', 'email.base64MIME', 'errno', '_socket', 'binascii', 'email.Utils',
 'sre_constants', 'email.MIMEMessage', 'email._parseaddr', 'email.sys',
 'apport.traceback', 'apt.package', 'apt.random', 'xml.dom.NodeFilter',
 'email.MIMENonMultipart', '_codecs', 'apport.unittest', 'apport.apt', 'email.os',
 'email.utils', 'pwd', 'apport.time', 'copy', '_struct', '_types', 'email.email',
 'apt.cdrom', 'uu', 'xml.dom.minidom', 'apport_python_hook', 'apt', 'email.random',
 'posix', 'encodings.aliases', 'apt.sys', 'fnmatch', 'sre_parse', 'pickle', 'copy_reg',
 'sre_compile', '_random', 'site', 'email.base64', 'apt.errno', '__main__', 'problem_report',
 'pyexpat', 'email.MIMEBase', 'email.message', 'string', 'email.mime.nonmultipart',
 'apport.subprocess', 'shutil', 'strop', 'grp', 'encodings.codecs', 'gettext',
 'email.warnings', 'xml.dom.minicompat', 'email.MIMEMultipart', 'types', 'apport.tempfile',
 'stat', '_ssl', 'warnings', 'encodings.types', 'glob', 'email.re', 'sys', 'email.Encoders',
 'readline', 'email.cStringIO', 'xml.dom', 'xml.dom.xml', 'apport.signal', 'sitecustomize',
 'email.mime.email', 'email.base64mime', 'email.mime.multipart', 'apport.packaging',
 'urlparse', 'linecache', 'email.string', 'apt.re', 'time', 'gzip']


And now, some useful functions with os module.
>>> print os.uname()
('Linux', 'mint', '2.6.27-7-generic', '#1 SMP Fri Oct 24 06:42:44 UTC 2008', 'i686')
>>> print os.ttyname(1)
/dev/pts/0
>>> print os.times()
(0.050000000000000003, 0.02, 0.0, 0.0, 17186002.649999999)
>>> print os.environ
{'USERNAME': 'root', 'LANG': 'en_US.UTF-8', 'TERM': 'xterm', 'SHELL': '/bin/bash',
 'XDG_SESSION_COOKIE': '842d38513df1a6bb7490c8a14bf69489-1274456064.963733-1686354756',
 'SUDO_COMMAND': '/bin/su', 'SHLVL': '1', 'RUNNING_UNDER_GDM': 'yes', 'SUDO_UID': '999',
 'SUDO_GID': '999', 'PWD': '/home/mint/Desktop', 'LOGNAME': 'root', 'USER': 'root',
 'COLORTERM': 'gnome-terminal',
 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games',
 'MAIL': '/var/mail/root', 'SUDO_USER': 'mint', 'HOME': '/root', 'DISPLAY': ':0.0',
 '_': '/usr/bin/python', 'XAUTHORITY': '/home/mint/.Xauthority'}
>>> print os.mkdir('aaa')
None
>>> print os.mkdir('aaa')
Traceback (most recent call last):
File "", line 1, in 
OSError: [Errno 17] File exists: 'aaa'
>>> print os.listdir('/')
['media', 'root', 'sbin', 'usr', 'lib', 'tmp', 'home', 'var', 'cdrom', 'etc',
 'rofs', 'bin', 'boot', 'dev', 'initrd.img', 'mnt', 'opt', 'proc', 'srv',
 'sys', 'vmlinuz']

These is just a brief tutorial about sys and os modules.

Wednesday, May 19, 2010

The beauty of Python: Simple functions - part 1

Validation of a condition and return result in 'Yes' or 'No'.

>>> def valid(x,y):
...     return ('Yes' if x==y else 'No') 
... 
>>> valid(2,3)
'No'
>>> valid(2,2)
'Yes'


Some usefull functions from string module .

>>> import string 
>>> var_template_string=string.Template(" The $subj $vb $something")
>>> var_template_string.substitute(subj="PC", vb="working", something="now")
' The PC working now'
>>> some_string_dictionary={'subj':'car', 'vb':'is', 'something':'blue'}
>>> var_template_string.substitute(some_string_dictionary)
' The car is blue'
>>> some_string_dictionary


Some example with re module and html tag

>>> import re
>>> t='<p>'
>>> some_tag = re.compile(r'<(.*?)(\s|>)')
>>> m = some_tag.match(t)
>>> print m
<_sre.SRE_Match object at 0xb7f79da0>
>>> dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start']
>>> print m.start()
0
>>> print m.groups()
('p', '>')
>>> print m.group()
<p>
>>> print m.span()
(0, 3)

The re module has many usefull functions.
This is just some examples to show the simplicity of python language.

Monday, March 1, 2010

Python and OpenGL - first steps

First you need to install python .
Second you need to install pyopengl module.
This is easy if we use some linux distributions.
On Fedora we can use command yum.
On Debian and Ubuntu we can use apt-get.
At last we need some basicaly examples.
We can get some examples from:PyOpenGL-Demo
But this is not all we will need more.
To go on next step we will need to read OpenGL specifications.
Try to use search on internet to see more about OpenGL.

Tuesday, February 23, 2010

How to display the "%" in python ?

I saw something interesting on the internet.
How to display the "%" in python.
I found so far two methods:


>>> print "See %d%%" % (0.77 * 100)
See 77%
>>> print "See {0:.0%}".format(0.77)
See 77%
>>>

Friday, February 12, 2010

Where is Santa Claus?

I wrote a python module. I called it "geo" because it is a geographic module.
The funny stuff is when i use it with "Santa Claus".

>>> import geo
>>> geo.adress("Santa Claus")
{'status': '200', 'latitude': '32.1715776', 'longitude': '-82.3315138', 'accuracy': '4'}

So where is Santa Claus ?!
Google Maps API should be prepared to respond.
Tomorrow a child will know how to use the Python language.
Who knows ...

Thursday, February 4, 2010

Parsing feeds - part 1

From time to time I used conky. Is good for me, because i have all i need on my desktop.
How helped me python in this case?
For example i use one script to parse a feed from this url:
"http://www.bnro.ro/nbrfxrates.xml"
The example is simple to understand :
from xml.dom import minidom as dom
import urllib
def fetchPage(url):
a = urllib.urlopen(url)
return ''.join(a.readlines())

def extract(webpage):
a = dom.parseString(webpage)
item2 = a.getElementsByTagName('SendingDate')[0].firstChild.wholeText
print "DATA ",item2
item = a.getElementsByTagName('Cube')
for i in item:
if i.hasChildNodes() == True:
eur = i.getElementsByTagName('Rate')[10].firstChild.wholeText
dol = i.getElementsByTagName('Rate')[26].firstChild.wholeText
print "EURO  ",eur
print "DOLAR ",dol

if __name__=='__main__':
webpage = fetchPage("http://www.bnro.ro/nbrfxrates.xml")
extract(webpage)
The result is:
$python xmlparse.py
DATA  2010-02-04
EURO   4.1214
DOLAR  2.9749
With "urllib" package I read the url.
The result is parsing with functions from "dom" package.
I used this functions "parseString" and "getElementsByTagName".
More about this functions you will see on:
http://docs.python.org/library/xml.dom.minidom.html
This is all.

Saturday, January 30, 2010

How to resize images .

Sometimes it is necessary to resize the images. The PIL module is used for image processing.The glob module takes a wildcard and returns the full path of all files and directories matching the wildcard.
Here are two scripts that I made.
The first is a simple example using a resize after some dimensions.
In this case we used size 300x300.

from PIL import Image
import glob, os
size_file = 300,300
for f in glob.glob("*.png"):
file, ext = os.path.splitext(f)
img = Image.open(f)
img.thumbnail(size_file, Image.ANTIALIAS)
img.save("thumb_" + file, "JPEG")

In the second case I tried to do a resize with proportion preservation.

import glob
import PIL
from PIL import Image
for f in glob.glob("*.jpg"):
img = Image.open(f)
dim_percent=(100/float(img.size[0]))
dim_size=int((float(img.size[1])*float(dim_percent)))
img = img.resize((100,dim_size),PIL.Image.ANTIALIAS)
if f[0:2] != "trumb_":
img.save("thumb_" + f, "JPEG")

In both cases we use a renaming of files by adding the name of "thumb_".
Ambele scripturi pot fi modificate asa cum vreti.
Aceste scripturi demonstreaza cum sa folosim celor doua module "PIL" si "globe".