Thursday 26 April 2012

Hello Python

In 2006 and 2007, I wrote a lot of Perl scripts. Having stopped using Perl since 2008, recently I find that it's very hard for me to understand those scripts I wrote 5 years ago.
So I decide to pick up a different language that is more intuitive. After googling around, I decided to give Python a try. I mainly write scripts to manipulate files and strings, So file IO and regular expression are the first two things I checked out.

First let's create a file called abc:
$ echo "Hello perl" > abc

Using sed, we can easily replace 'perl' with 'python'
$ sed 's/perl/python/'  abc

To do it in Python, we can use this script
#!/usr/bin/python

import os
import re
import string

fr = open('abc', 'r')
mystr = fr.read()
fr.close()

str_by_sub = re.sub('perl', 'python', mystr)
str_by_replace = string.replace(mystr, 'perl', 'python')

fw = open('def','w')
fw.write(mystr)
fw.write(str_by_sub)
fw.write(str_by_replace)
fw.close()

After executing the script, we will have a file called def, the content would be
Hello perl
Hello python
Hello python
There are other parameters with string.replace and re.sub, which control the behaviors of the replacement, I still need further reading to understand them better.

It was very intuitive to write my first Python script, I think I will like Python :)

No comments:

Post a Comment