Python Tutorial

Friday, December 9, 2011

Sqlite in python

Using Sqlite in python is very simple. Sqlite installed default with python 2.5+
I use SQLite Manager for sqlite
Lets goto the example:


import sqlite3 as sqlite
#Connect to the file 'pythonSqliteExample.sqlite'
connection = sqlite.connect("pythonSqliteExample.sqlite")
#Get the cursor
cur=connection.cursor()
cur.execute("select * from info")

for row in cur:
    print "name: ",row[0]," address ",row[1]," score",row[2]

cur.execute("insert into info values ('TJ','BD',50)")
#This is for save the chages
connection.commit()
print "After Commit"
cur.execute("select * from info")

for row in cur:
    print "name: ",row[0]," address ",row[1]," score",row[2]

connection.close()
 


Output

 
name:  tom  address  bangladesh  score 10
name:  jerry  address  bangladesh  score 5.5

After Insert
name:  tom  address  bangladesh  score 10
name:  jerry  address  bangladesh  score 5.5
name:  TJ  address  BD  score 50
 
 


I upload full code with database here You can use it.

Thursday, August 11, 2011

python reqular expression re.findall()

re.findall() is very similar to re.search. Only difference is re.search() looking for first instance but re.findall() for all instance match with this expression.
Lets see some example:
import re 

#find all one or more r
m=re.findall(r'r+','tomorrow rrow RRO')
print m

#find all one or more r ignorecase
m=re.findall(r'r+','tomorrow rrow RRO',re.IGNORECASE)
print m

#find all two consecutive digits
m=re.findall(r'\d\d','tomorrow123  foo89')
print m

#find all email from string
m=re.findall(r'[\w.-_]+@[\w.]+','test 123 . @ test.cse@gmail.com test
test@yahoo.com test_tester@yahoo.com test-123@yahoo.com') print m



Output:
['rr', 'rr']
['rr', 'rr', 'RR']
['12', '89']
['test.cse@gmail.com', 'test@yahoo.com', 'test_tester@yahoo.com', '123@yahoo.com']

python reqular expression re.search()

re.search() is used for search pattern into string, it's return the corresponding match object. Let's got to some example:

At first we need to write a function named printMatch, i think very shortly you will know why this function is for :)


import re

def printMatch(m):
    if m:
        print m.group(0)
    else:
        print "Not Found"

#search one or more r
m=re.search(r'r+','tomorrow')
printMatch(m)

#search two consecutive digits
m=re.search(r'\d\d','tomorrow123')
printMatch(m)

#after find a digit go rest of the word
m=re.search(r'\d\w+','tomorrow123 foo')
printMatch(m)

#need to match from start index
m=re.search(r'^\d\w+','tomorrow123 foo')
printMatch(m)

#need to match from start index
m=re.search(r'^\d\w+','456tomorrow123')
printMatch(m)

#only search for non numeric character
m=re.search(r'\D*','tomoRRo._+#w123 foo')
printMatch(m)

#try yourself
m=re.search(r'\d*\s*\d*\s','tom123    45 foo')
printMatch(m)

#filter email address from string
m=re.search(r'[\w.]+@[\w.]+','test 123 . @ jony.cse@gmail.com test')
printMatch(m)

#any character after m
m=re.search(r'm.+','tomorrow foo')
printMatch(m)




Output:
rr
12
123
Not Found
456tomorrow123
tomoRRo._+#w
123    45 
jony.cse@gmail.com
morrow foo



Finally:
There are lots of way to use re.search() in python, I am just showing you some them. Hope it will help you to explore it.

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