Python Tutorial

Friday, November 23, 2012

Design pattern in python : Factory method


Factory method pattern in python.
All source code available on github

class Book:
    def book_category(self):    pass

class PythonBook(Book):
    def book_category(self):
        print "Python book"

class JavaBook(Book):
    def book_category(self):
        print "Java book"

class BookFactory:
    def get_book(self, book_type):
        if book_type=='python':
            return PythonBook()
        elif book_type=='java':
            return JavaBook()
        else:
            return None

bookFactory = BookFactory()
pythonBook = bookFactory.get_book('python')
pythonBook.book_category()

javaBook = bookFactory.get_book('java')
javaBook.book_category()



Output:
Python book
Java book

Design pattern in python: Template method


Template method design pattern in python.
All source code available on github

class MakeMeal:

    def prepare(self):  pass
    def cook(self): pass
    def eat(self):  pass

    def go(self):
        self.prepare()
        self.cook()
        self.eat()

class MakePizza(MakeMeal):

    def prepare(self):
        print "Prepare Pizza"

    def cook(self):
        print "Cook Pizza"

    def eat(self):
        print "Eat Pizza"

class MakeTea(MakeMeal):

    def prepare(self):
        print "Prepare Tea"

    def cook(self):
        print "Cook Tea"

    def eat(self):
        print "Eat Tea"

makePizza = MakePizza()
makePizza.go()

print 25*"+"

makeTea = MakeTea()
makeTea.go()



Output:
Prepare Pizza
Cook Pizza
Eat Pizza
+++++++++++++++++++++++++
Prepare Tea
Cook Tea
Eat Tea

hashlib : secure hashes and message digests


hashlib implements many different secure hash and message digest algorithms(SHA1, SHA224, SHA256, SHA384, SHA512, MD5). Lets have a look...

 
import hashlib

message = "python"

print "md5"
print hashlib.md5(message).hexdigest()

print "sha1"
print hashlib.sha1(message).hexdigest()

print "sha512"
print hashlib.sha512(message).hexdigest()

print "sha224"
print hashlib.sha224(message).hexdigest()

print "sha256"
print hashlib.sha256(message).hexdigest()

print "sha384"
print hashlib.sha384(message).hexdigest()



Output:
md5
23eeeb4347bdd26bfc6b7ee9a3b755dd
sha1
4235227b51436ad86d07c7cf5d69bda2644984de
sha512
ecc579811643b170cbd88fd0d0e323d1e1acc7cef8f73483a70abea01a89afa8015295f617f27447ba05e928e47a0b3a46dc79e72f99d1333856e23eeff97d8b
sha224
dace1c32d56e6f2bd077266a5a381fcf7ff9052e0a269e32cd52a551
sha256
11a4a60b518bf24989d481468076e5d5982884626aed9faeb35b8576fcd223e1
sha384
2690f7fce3051903a4e8b9f1f9ea705f070f03f9d84c353f2653cece80ea68130ef8defd53ef29af5f236e6cac7c7efb

Monday, November 19, 2012

python FuzzyWuzzy : Levenshtein distance


FuzzyWuzzy is very easy to use. Lets see some example.
All source code available on github

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

print fuzz.ratio("this is a test", "this is a test!") # sample ratio
print fuzz.partial_ratio("this is a test", "this is a test!") # partial ratio
# token sort ratio
print fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")

print "Process"
choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"]
print process.extract("new york jets", choices, limit=2) # find best two choices
print  process.extractOne("cowboys", choices) # find best choice


Output:
97
100
100
Process
[('New York Jets', 100), ('New York Giants', 79)]
('Dallas Cowboys', 90)

Python FuzzyWuzzy : string matching


FuzzyWuzzy find Levenshtein distance between strings. It is very handy for dealing with human-generated data.

Install:
pip install -e git+git://github.com/seatgeek/fuzzywuzzy.git#egg=fuzzywuzzy

Sunday, November 18, 2012

python dateutil : date operation is fun


Here some example code of operate date with dateutil. It very easy, reduce lots of pain & code. I think from now you like date operation much.
All source code available on github

 
from dateutil.parser import parse
from dateutil.relativedelta import *

from datetime import *
print "parse example"
print parse('Mon, 11 Jul 2011 10:01:56 +0200 (CEST)')
s = "Today is 25 of September of 2003, exactly at 10:49:41 with timezone -03:00."
print parse(s, fuzzy=True)


today = datetime.now()
print 20*"=="
print today # today
print today+relativedelta(months=+1) # Next month
print today+relativedelta(years=+1) # Next year
print today+relativedelta(months=+1, weeks=+1) # Next month, plus one week
print today+relativedelta(months=+1, weeks=+1, hour=10) # Next month, plus one week, at 10am
print today+relativedelta(years=+1,months=-1) # One month before one year

print 20*"++"
print today+relativedelta(weekday=FR) # Next friday
print today+relativedelta(days=+1,weekday=SU(+1)) # Next sunday, but not today
print today+relativedelta(day=31, weekday=FR(-1)) # Last friday in this month


print "Calculate Age"
birthday = datetime(1971, 4, 5, 12, 0)
age = relativedelta(today, birthday)  # calculate age
print age
print "years: ",age.years," months: ",age.months," day: ",age.days




Output:
parse example
2011-07-11 10:01:56+02:00
2003-09-25 10:49:41-03:00
========================================
2012-11-18 23:35:31.191000
2012-12-18 23:35:31.191000
2013-11-18 23:35:31.191000
2012-12-25 23:35:31.191000
2012-12-25 10:35:31.191000
2013-10-18 23:35:31.191000
++++++++++++++++++++++++++++++++++++++++
2012-11-23 23:35:31.191000
2012-11-25 23:35:31.191000
2012-11-30 23:35:31.191000
Calculate Age
relativedelta(years=+41, months=+7, days=+13, hours=+11, minutes=+35, seconds=+31, microseconds=+191000)
years:  41  months:  7  day:  13

python dateutil


Python dateutil module provides powerful extensions to the standard datetime module. It reduce pain of handling date. Here main tutorial page.

Install:
pip install python-dateutil