Python Tutorial

Friday, July 22, 2011

Python:Url Fetch

Python URL Request Response
Some times when we try to fetch url directly server does not return page content. For this reason we need to request the server first then read the page using this response. A sample code of python request response is given below.
We can also set some others additional parameter as timeout, max redirect so on
import urllib2
def get_url_content(site_url):
    rt=""
    try:
        request = urllib2.Request(site_url) 
        f=urllib2.urlopen(request)
        content=f.read()
        f.close()
    except urllib2.HTTPError, error:
        content=str(error.read())
    return content

Thursday, July 21, 2011

Date time

Python date time comparison:
For python date time comparison you can directly compare between two date and also make some mathematical operation
import datetime
import time
before=datetime.datetime.now()
print "before "+str(before)
time.sleep(5)
after=datetime.datetime.now()
print "after "+str(after)
difference=after-before
print "difference "+str(difference)



before 2011-07-21 15:38:13.330000
after 2011-07-21 15:38:18.347000
difference 0:00:05.017000

String split by length

Python String split by length:
some time we need to split string by length, sample code is given below

def split_by_length(s,block_size):
    w=[]
    n=len(s)
    for i in range(0,n,block_size):
        w.append(s[i:i+block_size])
    return w
w=split_by_length("ABCDEFGHIJKLMNOPQRSTUVWXYZ",5)
print w




Output:

['ABCDE', 'FGHIJ', 'KLMNO', 'PQRST', 'UVWXY', 'Z']

Tuesday, June 21, 2011

Python regular expression example: Sample url checker

Using regular expression in python:
Let write a sample url checker, each url have three parts separated by dot(.), first part must have www
secound part have at leat one characher between a to z or A to Z or 0 to 9 and third part must have com

import re
def myRegularExpressionChecker(expression,data):
    reg=re.compile(expression);
    if reg.match(data):
        return 'Yes'
    return 'No'

print myRegularExpressionChecker('www[.][a-zA-Z0-9]+[.]com','www.google.com')
print myRegularExpressionChecker('www[.][a-zA-Z0-9]+[.]com','www.cs.edu')
print myRegularExpressionChecker('www[.][a-zA-Z0-9]+[.]com','www.123cseASD.com')
print myRegularExpressionChecker('www[.][a-zA-Z0-9]+[.]com','www.123google.com')
print myRegularExpressionChecker('www[.][a-zA-Z0-9]+[.]com','www.google_123.com')
print myRegularExpressionChecker('www[.][a-zA-Z0-9]+[.]com','www.google.123.com')
Output
 
 Yes
 No
 Yes
 Yes
 No
 No
 
 

Monday, June 20, 2011

Mysql in python: Fetch data

From the code below it's very clear that you need to create a database first named py_sample_db
Then you need to create a table named sample_py_table with two colums (name,email), all contents are varchar type.

You can also run this code on your own database
A sample table:
name email
jonyabu@yahoo.com
jonyzahed@yahoo.com


 '''
  This code use python MySQLdb syntax
 '''

 import MySQLdb
 conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "",db = 
"py_sample_db") cursor = conn.cursor () sql="SELECT * from sample_py_table where name='jony'"; cursor.execute (sql) rows = cursor.fetchall () for row in rows: print "%s, %s" % (row[0], row[1]) cursor.close () conn.close () print "Fetch success"
Output
 
 jony, abu@yahoo.com
jony, zahed@yahoo.com

Mysql in python: Insert

From the code below it's very clear that you need to create a database first named py_sample_db
Then you need to create a table named sample_py_table with two colums (name,email), all contents are varchar type.
You can also run this code on your own database by changing current settings(host,user,passwd,db)


 '''
  This code use python MySQLdb syntax
 '''

 import MySQLdb
 conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "",db =
"py_sample_db") cursor = conn.cursor () sql="INSERT into sample_py_table (name,email) VALUES ('jony','myemail@gmail.com1')"; cursor.execute (sql) cursor.close () conn.close () print "Insert success"

Mysql in python: Install

Python database(MySql) syntax is very easy. For MySql in python you need some aditional libraries.

For linux: install MySQL-Python

For Xp: install Install MySQL-python-1.2.3.win32-py2.7.exe

Now I am using python 2.7