analitics

Pages

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".