The Python Ecosystem

     REGULAR EXPRESSION :   Built in “re” module in Python

            Pattern matching for strings ,   Find and Replace using search patterns   ( Regex or Regexp ), Split into multiple smaller …..  Use of regex as  very fast

            Each character in the regular expression is a meta character with special meaning or a regular character with its literal meaning

                   import re , 

                    s =  re.search (pattern, text )  returns the Match object and returns the start and end position   …  s.start(), s.end(), s.groups, s.span()

                    re.findall   ( returns all objects from the string ) , 

                    re.match ( finds if in the beginning ) 

                    re.compile   Used to compile a regular expression pattern into pattern objects, which can be used in matching , more efficient.

                                   s = re.compile(‘test’)    match = s.search(‘testing’)  match.group()

                    re.sub  Used to replace substrings    Example re.sub(pattern, repl, string)     re.sub(‘gmail’, ‘yahoo’, ‘ This is hello@gmail.com’)

 

                   Examples :

                        re.search(r’ Word1|Word2′ ,  text )  finds word1 or word2 ….   

                         r'(a[a-z]+’)    ……    r’\bThis\b‘    (Searches whole word )     ‘r  at beginning of the pattern string, represents a python ‘raw’ string

                         [abc] matches ‘a’, ‘b’ or ‘c’

                         [^abc]  matches any single character except ‘a’, ‘b’ or ‘c’

                         (abc)+   parenthesis matches ‘abc’, ‘abcabc’  …      

                         (a|b)      or  

                         x*     zero or more matches  ‘ ‘ , ‘x’, ‘xx’ …

                         x+    matches one or more   ‘x’,’ ‘xx’

                         x?     matches zero or more ‘ ‘ or ‘x’

                        x{2,3}  matches ‘xx’, ‘xxx’  

                        \d     matches any digit ,  \D   matches any non digit

                       \s      matches any white space character,  \S matches any not whitespace character 

                       \w    matches any alphanumeric character \W matches any not alphanumeric character

                       ^        matches the beginning of the string,  $ matches the end of the string

                       \b    matches a  word boundary  \B matches position that is a non word boundary     

                      re.search(‘ (test).*(i[a-z]+)’ , test)

                      re.findall(r'[\w\.-]+gmail[\w\.-]+’, f.read())      find all gmail emails in a file             

 

               Getting emails from a page 

                   import urllib2 

                      site = urllib2.urlopen(r’http://www.mydj.in’)

                      text = site.read()

                       urlstr = re.compile(r’http[s]*://[a-z|A-Z|0-9|.|/|~|?]+[.]+[a-z]+’)

                       emails = re.compile(r'[a-z|A-Z]+[a-z|A-Z|.|_|-|0-9]*@[a-z]+.[a-z]+’)

                      set(re.findall(emails, text))

                Returning XML Contents 

                       Example 1 : 

                        xml = “<xml> <Customer>Test</Customer></xml>”

                        s = re.search(r'<(xml)><(.*)>(.*)</\2></\1>’,xml)

                        s.groups()     print(s.group(1) + “:” s.group(2) )

                      Example 2 :

                       f =  open (‘filename.xml’)   for  i in file:          data= re.search(r1<([a-z]+)>(.*)</\1>’, i)     print(data.group(1) + “:” + data.group(2) )

 

Object Oriented Programming in Python 

                     CLASS: 

                              Defined by simply    

                                Class  Account:                                      /Note :  Python by default assigns attributes and methods to this class. Example: dir(Account)

                     

                        ATTRIBUTES     ( private, static )      

                                  a =  10                                                / a Equivalent to static variable, available to all objects of the class

                                      def  __init__(self, param1= 10):     /  Constructor in  python (__init__)  …  

                                             self.b = param1                        /  b becomes the attribute of the object in the class ……   self is also equivalent to this

                              Note :   YOU CAN CREATE CLASS AND INSTANCE VARIABLES ON THE FLY 

                             obj = Account()                                           /  Creating a object of class Account

                             obj.c = “test”                                                /  Creating a new object variable for this object 

                             Account.d = “hello”                                    /  Creating a class variable using the object,   This will make add the variable to all the existing objects

                             

                             Accessing a non existing attribute raises an AttributeError

 

 

                        METHODS :

                             PUBLIC, STATIC, PROTECTED METHODS 

                                           class  Customer:        

                                            def  __init__( UserId,   UserName):                                                                                     /Constructor and private method

                                                         self.id = UsedId      self.name = UserName

                                            def  __del__(self) :                                                                                                                 / Destructor, Called when object is destroyed

                                           def   displayCustomer(self, id):     print id.name                                                                          /Public Method   First parameter should be self

                                          @staticmethod 

                                          def   defaultName(UsedId, UserName) : print ( UserId + “:” + UserName)                        / Static Method

                                            Customer.defaultName( 1, ‘John’)             Output:  1 : John                        /  This static method can be called from outside without creating an object 

                                              

                                          def   _rankCustomer_(   ):                                                                                /  Protected Method

                                         def    __encryptCustomer__()                                                                          /  Private Method

                                         self._rank  = 0                                                                                                   /    Protected Attribute

                                         self.__encrypted = “Yes”                                                                              /    Private Attribute

 

 

                         BUILT-IN  CLASS ATTRIBUTES

                                __dict__  :             Contains Class’s Namespace 

                                __doc__  :              Contains Class’s documentation

                                __name__ :             Contains Class’s Name

                                __module__ :          Module the class belongs to

                                __bases__   :           Empty tuple containing the base classes 

 

 

             ENCAPSULATION,  INHERITANCE AND POLYMORPHISM 

                       Encapsulation :   Encapsulate attributes and methods to close to the object to protect them, provide abstraction  and maintain integrity of the object

                        By default Python creates getters and setters 

 

                      Inheritance : 

                           – Single inheritance :    Class A inherits from Class B

                                             SYNTAX :    class DerivedClassName (BaseClassName1,  BaseClassName2)   

                                              class base:  def  test(self):   print(‘ I am a base class’)

                                             class derived( base ):    def mytest(): pass   

                                             obj = dertived()    obj.test()

                           –  Multi Level  Inheritance :   Class A inherits from Class B and Class C inherits from Class B

                           –  Hierarchical Inheritance :  Class B and Class C inherit from Class A

                           –  Multiple Inheritance :   Class C inherits from Class A and Class B      / Note if same method exists in both Class A and Class B,  the first class method will be called 

 

                    Polymorphism:  ( Meaning Many Forms ) 

                       Provide a single interface to entities of different types  or use of symbol to represent multiple different types 

                          Example :   Overload same operator to perform different operations.     + operator  can be used on an integer or used on a string

                        Python is implicitly polymorphic

                        Overloading special functions in python   __init__  __add__  __repr__      __len__  __del__  __str__