Python Tutorial

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