Thursday, November 27, 2008

How to write something in PDF by python

Did you ever meet this problem?your customer want to show their report by PDF format.I think so.I think the best lib to use is ReportLab ,you can download it from site and install it.Today I want to provide an simple example to illustrate how to use it,especially when you write something none standard character in it.Let's begin with a real example in our app,suppose you want to convert a text to a PDF.now you have a file at c:/log.txt,and you want to covert it to c:/h.pdf file.The code is :

#first we import necessary module.
from reportlab.pdfgen import canvas
#now,open the file which we want to covert to
f=open("c:/log.txt","rb")
#read each line in the file.
lines=f.readlines()
#create a canvas objects,it can write the string
#in the pdf
c=canvas.Canvas("c:/h.pdf")

#maybe the file we read was very big so we must
#consider that display them in multiple page
j=700 #for example it's height is 700 point
for row in lines:
#firstly, we do an encoding cover.
uniline=unicode(row,'latin-1')

if j==0:
j=700
#showPage method means,we want to write in next page
c.showPage()
else:
j=j-10
#drawString method will draw the text information in PDF
c.drawString(100, j, uniline.strip())
#don't forget close the file
f.close()
#don't forget save the canvas,otherwise,you can't see anything
#in the .pdf file
c.save()

It's simple that is,right?

Wednesday, November 26, 2008

The order of the Python's class inheritance

Every OOP language provide the inheritance feature.In Python one subclass could have multiple super class,For example:we have two class A and B,now we create another class C,it's inherit from A and B:
class A:
def method1(self):
print "this is the method1 of class A"
class B:
def method1(self):
print "this is the method2 of class B"
class C(A,B): #class C inherit from A and B
pass


c=C()
c.method1()#Now the question is which method will be call,A or B
#The result is:
this is the method1 of class A

That means,the inheritance rest with which super class in the starting location,in this example,class A in the zero position,so the method1 in class A will be call instead of class B

Tuesday, November 25, 2008

A better way to create your own python path

When we program we have to create our own module,sometime we just want to test some feature,and then write a series of .py file.We want to use them conveniently.So I think a better way to do this is create a .pth file,then save it in the top level of python program.For example:
we create a file mypath.pth,then save it into c:/python25
edit this file like:
D:\my-python-module\

Then when we put new .py file in this folder, we can reuse them as they are the standard python module.

Sunday, November 23, 2008

Function argument-matching forms In Python

Syntax

Location

Interpretation

func(value)

Caller

Normal argument: matched by position

func(name=value)

Caller

Keyword argument: matched by name

def func(name)

Function

Normal argument: matches any by position or name

def func(name=value)

Function

Default argument value, if not passed in the call

def func(*name)

Function

Matches remaining positional args (in a tuple)

def func(**name)

Function

Matches remaining keyword args (in a dictionary

Python's object reference

I talk about this subject because the way to stuff arguments in Python is special.Considering following code:
list1=[1,2,3]
str1="hello"
def f2(x,y):
list1.append(4)
y="world"

f2(list1,str1)
list1 #the value is [1,2,3,4],it's changed
str1 # the value is "hello",str1 is not changed

Because Python's argument is the object reference,so if you stuff a mutable object,its value will be change in place.sometime if you want to avoid your outside variable changed by function,you can pass a copy of mutable object to the function:
list1=[1,2,3]
str1="hello"
def f2(x,y):
list1.append(4)
y="world"

f2(list1[:],str1) #Now,we assign a list1[:],it's the copy of list1
list1 #the value is [1,2,3],it's not changed
str1 # the value is "hello",str1 is not changed

Or we can use tuple keyword,convert an array object to a tuple object:
list1=[1,2,3]
str1="hello"
def f2(x,y):
list1.append(4)
y="world"

f2(tuple(list1),str1) #Now,we assign a tuple,it's convert from list1
list1 #the value is [1,2,3],it's not changed
str1 # the value is "hello",str1 is not changed

The global statement

Today I want to talk about the global statement in Python.Since I'm a java programmer,so I usually like to compare the difference between python and java.Now I want to talk about the global statement.In Java all stuff placed into a class file,so if you want to change a class level variable in a method,you can simply assign a new value to this variable.for example:
class Test{
private String x=null;//declare a new variable:x
public change_variable(){
x="hello" //change the outside variable inside the method
}
}
but if you think you can change a module level variable in Python, you are totally wrong.please see following:
#python code
x=99 #this is a global variable
#define a function
def func():
x=100

func() #call this function
print x # what's happened? x=99 or x=100

#the truth is x=99


Why is that,because when you use a same variable name in the function,Python will create a new local variable instead of use the global variable,so the global x is not changed.Then,if you really want to change the global variable,you must use the global keyword:
#python code
x=99 #this is a global variable
#define a function
def func():
global x #now it seems as we declare that we'll use the global x
x=100

func() #call this function
print x # what's happened? x=99 or x=100

#now x=100

Thursday, November 20, 2008

How to find you win32ui.pyd


Did you ever have this problem,when you install the Activity Python and run Python win,you will got an exception:'The application cannot locate win32ui.pyd ...'.
To solve it,we just need download and install another python library,pywin32.to download it from https://sourceforge.net/projects/pywin32/ and setup it.

Wednesday, November 19, 2008

How to use zip and map function

There are many core build-in function in Python,today we'll meet zip and map.to illustrate,for instance,you have to list object,l1 and l2,now by use zip function you will get a tuple embeded list:
#python code:
>>> l1=['x','y','z']
>>> l2=[1,2,3]
>>> zip(l1,l2)
[('x', 1), ('y', 2), ('z', 3)]
>>>

Now,you can loop in this new zip model,and have the benefit from it,for example,you want to loop in these two list at the same time:
#python code:
>>> for (a,b) in zip(l1,l2):
print a,b


x 1
y 2
z 3
>>>

With this benefit,we can also create a dictionary object,for example:
#python code:
>>>d={}
>>> for (k,v) in zip(l1,l2):
d[k]=v
print d


{'x':1,'y':2,'z':3}
>>>

also there is a short way to create a dictionary object,use the build-in function,dict:
#python code:
>>>d={}
>>> d=dict(zip(l1,l2))
{'x':1,'y':2,'z':3}
>>>


Now,how about map function,map function is similar to zip,but for zip if your two list object has different number of items,then the zip function will truncate the larger one.for example:
#python code:
>>>l1=['x','y']
>>>l2=[1,2,3]
>>>zip(l1,l2)
>>>[('x',1),('y',2)]


but if you use the map function,you can stuff another parameter,to tell the function how to display that can't match items:
#python code:
>>>l1=['x','y']
>>>l2=[1,2,3]
>>>map(l1,l2)
>>>[('x',1),('y',2),(None,3)]

Print to a file,a simple log system

There is many of log system in this time.Use python we can create a very simple log system.The way is use print function and >> operator.
Here is the example code:
#python code
>>log=open('c:/log.txt','a') #open a file to log the message
>>print>>log,"This is log information" #then we put the log information to a file
>>log.close() # don't forget close the file

Tuesday, November 18, 2008

Comparisons,Equality in Python

All python objects also respond to comparison.

For instance, a comparison of list objects compares all their components automatically:

>>> L1 = [1, ('a', 3)]         # Same value, unique objects
>>> L2 = [1, ('a', 3)]
>>> L1 == L2, L1 is L2 # Equivalent? Same object?
(1, 0)

Here, L1 and L2 are assigned lists that are equivalent, but distinct objects. Because of the nature of Python references (studied in Chapter 4), there are two ways to test for equality:

  • The == operator tests value equivalence. Python performs an equivalence test, comparing all nested objects recursively

  • The is operator tests object identity. Python tests whether the two are really the same object (i.e., live at the same address in memory).

In the example, L1 and L2 pass the == test (they have equivalent values because all their components are equivalent), but fail the is check (they are two different objects, and hence two different pieces of memory). Notice what happens for short strings:

>>> S1 = 'spam'
>>> S2 = 'spam'
>>> S1 == S2, S1 is S2
(1, 1)

Here, we should have two distinct objects that happen to have the same value: == should be true, and is should be false. Because Python internally caches and reuses short strings as an optimization, there really is just a single string, 'spam', in memory, shared by S1 and S2; hence, the is identity test reports a true result. To trigger the normal behavior, we need to use longer strings that fall outside the cache mechanism:

>>> S1 = 'a longer string'
>>> S2 = 'a longer string'
>>> S1 == S2, S1 is S2
(1, 0)

Friday, November 14, 2008

Improve the performance of you string

As we know,Python's string object is immutable,that means you can't change it in-place.Each time when you operate on a string it'll generate a new string object.Sometime it's not good,especially when your string is big.A method to solving this performance issue is use List object.first we convert a string to a list,now it's mutable ,secondly we manipulate this list,if it's done we convert to string.following is an example:
#Python code
#firstly, we define a new string,it's a poem ,a big string
bigstring=""""
Today I saw a butterfly,
as it floated in the air;
Its wings were spread in splendor,
Unaware that I was there.
""""
#secondly, we convert it to a list
biglist=bigstring.split(' ')
biglist[1]='you'
biglist[3]="one"
#convert it back
bigstring=''.join(biglist)
bigstring

Because list is mutable,each time we operate on it,no new object generated.So we have high performance.

Thursday, November 13, 2008

How to read and write the CSV file

We can do everything in Python mostly.today we'll show how to read and write csv file by Python.The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it.Python provide a lib which name csv to manipulate csv file.I think the best way to understand a new technology is an example,now let's see how to read a csv file.
#Python code:
import csv # first we need import necessary lib:csv
file=open("c:/Book1.csv") #prepare a csv file for our example

testReader=csv.reader(file,delimiter=' ', quotechar='|')
#now the testReader is an array,so we can iterate it
for row in testReader:
print "|".join(row)

#The result is:
Test1:Test1
Test2:Test2
.....

Mostly the value of a csv file will separate by comma,but sometime may be other App will generate a csv file and separate other quotechar(|,! etc).So csv lib provide a parameter :delimiter and quotechar, so you can custom it by yourself.
Now let's see how to write something into a csv file:
#Python code:
import csv # first we need import necessary lib:csv
file=open("c:/Book1.csv") #prepare a csv file for our example

testWriter = csv.writer(open('Book1.csv', 'w'), delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow(['Test'] * 5 + ['Wow'])
spamWriter.writerow(['Hello', 'I'm', 'Super Star'])


It's that easy,right?

Wednesday, November 5, 2008

NumPy :a powerful computing library

In my recently project,we plan to develop a financial system.There are many of mathematical computing in it.For performance reason, we need a high speed,fixable,reliable and efficient library.We estimate many libs ,in the end we decide to use Numpy,we highly recommend it.As the introduce of them:

The fundamental package needed for scientific computing with Python is called NumPy. This package contains:

  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • basic linear algebra functions
  • basic Fourier transforms
  • sophisticated random number capabilities
  • tools for integrating Fortran code.
  • tools for integrating C/C++ code.

Immutability or mutability

As a programmer I develop many of application,using Java,C++,Python and Ruby.Today I want to talk about the "mutability" in these different language.Let's begin with Python language,Python is a dynamic language different to Java or C++.but as we talk about mutability,especially "string" of them.it's same.In python every object is is classified as mutable or immutable.or we can call them "changeable" or "unchangeable".For instance,We have a string "Spam",in Python you can create it as:
>>s="Spam"
"Spam"

In Java you can declare it as:
String s="Spam"

Now,the requirement is we want to access the sub-string of them:
#Python code
>>> s="Spam"
>>> s[0]
'S'
>>> s[0]="z"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

As you can see,we can access Python string as a sequence by use 'index'but if we want to assign a new value into the item of this string we got an exception,that means the string object in Python is immutable,it's similar to Java and C++,but it's different to Ruby.In Ruby you can assign a new value into the item of a string,and after assignment ,the original string object changed:
#Ruby code
irb(main):001:0> s="Spam"
=> "Spam"
irb(main):002:0> s[0]
=> "S"
irb(main):003:0> s[0]="z"
=> "z"
irb(main):004:0> s
=> "zpam" #the value of s has been changed.

That means the string object is mutable in Ruby.In terms of the core types, numbers, strings, and tuples are immutable; lists and dictionaries are not (they can be changed in-place freely).