Python Modules & Regular Expressions

 Python Modules

A python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.

Example

In this example, we will create a module named as file.py which contains a function func that contains a code to print some message on the console.
Let's create the module named as file.py.

  1. #displayMsg prints a message to the name being passed.   
  2. def displayMsg(name)  
  3.     print("Hi "+name);    
Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.

Loading the module in our python code

We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.
  1. The import statement
  2. The from-import statement

The import statement

The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the functionality of any python source file by importing that file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into our file.
The syntax to use the import statement is given below.

  1. import module1,module2,........ module n  
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to import that file as a module into our module as shown in the example below.

Example:

  1. import file;  
  2. name = input("Enter the name?")  
  3. file.displayMsg(name)  
Output:
Enter the name?John
Hi John

The from-import statement

Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from? import statement. The syntax to use the from-import statement is given below.

  1. from < module-name> import <name 1>, <name 2>..,<name n>   
Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.

calculation.py:

  1. #place the code in the calculation.py   
  2. def summation(a,b):  
  3.     return a+b  
  4. def multiplication(a,b):  
  5.     return a*b;  
  6. def divide(a,b):  
  7.     return a/b;  

Main.py:

  1. from calculation import summation    
  2. #it will import only the summation() from calculation.py  
  3. a = int(input("Enter the first number"))  
  4. b = int(input("Enter the second number"))  
  5. print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation()  
Output:
Enter the first number10
Enter the second number20
Sum =  30

The from...import statement is always better to use if we know the attributes to be imported from the module in advance. It doesn't let our code to be heavier. We can also import all the attributes from a module by using *.
Consider the following syntax.

  1. from <module> import *   

Python packages

The packages in python facilitate the developer with the application development environment by providing a hierarchical directory structure where a package contains sub-packages, modules, and sub-modules. The packages are used to categorize the application level code efficiently.
Let's create a package named Employees in your home directory. Consider the following steps.

1. Create a directory with name Employees on path /home.

2. Create a python source file with name ITEmployees.py on the path /home/Employees.
ITEmployees.py

  1. def getITNames():  
  2.     List = ["John""David""Nick",    "Martin"]  
  3.     return List;  

3. Similarly, create one more python file with name BPOEmployees.py and create a function getBPONames().

4. Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a package, we need to include one more file here, that is __init__.py which contains the import statements of the modules defined in this directory.
__init__.py

  1. from ITEmployees import getITNames  
  2. from BPOEmployees import getBPONames  

5. Now, the directory Employees has become the package containing two python modules. Here we must notice that we must have to create __init__.py inside a directory to convert this directory to a package.

6. To use the modules defined inside the package Employees, we must have to import this in our python source file. Let's create a simple python source file at our home directory (/home) which uses the modules defined in this package.

Test.py

  1. import Employees  
  2. print(Employees.getNames())  
Output:
['John', 'David', 'Nick', 'Martin']

We can have sub-packages inside the packages. We can nest the packages up to any level depending upon the application requirements.
The following image shows the directory structure of an application Library management system which contains three sub-packages as Admin, Librarian, and Student. The sub-packages contain the python modules.


Python Regular Expressions

The regular expressions can be defined as the sequence of characters which are used to search for a pattern in a string. The module re provides the support to use regex in the python program. The re module throws an exception if there is some error while using the regular expression.
The re module must be imported to use the regex functionalities in python.

  1. import re   

Regex Functions

The following regex functions are used in the python

SNFunctionDescription
1match
This method matches the regex pattern in the string with the optional flag. It returns true if a match is found in the string otherwise it returns false.
2searchThis method returns the match object if there is a match found in the string.
3findallIt returns a list that contains all the matches of a pattern in the string.
4splitReturns a list in which the string has been split in each match.
5subReplace one or many matches in the string.

Forming a regular expression

A regular expression can be formed by using the mix of meta-characters, special sequences, and sets.

Meta-Characters

Metacharacter is a character with the specified meaning.
MetacharacterDescriptionExample
[]It represents the set of characters."[a-z]"
\It represents the special sequence."\r"
.It signals that any character is present at some specific place."Ja.v."
^
It represents the pattern present at the beginning of the string.
"^Java"
$It represents the pattern present at the end of the string."point"
*
It represents zero or more occurrences of a pattern in the string.
"hello*"
+
It represents one or more occurrences of a pattern in the string.
"hello+"
{}The specified number of occurrences of a pattern the string."java{2}"
|It represents either this or that character is present."java|point"
()Capture and group

Special Sequences

Special sequences are the sequences containing \ followed by one of the characters.
CharacterDescription
\A
It returns a match if the specified characters are present at the beginning of the string.
\b
It returns a match if the specified characters are present at the beginning or the end of the string.
\B
It returns a match if the specified characters are present at the beginning of the string but not at the end.
\dIt returns a match if the string contains digits [0-9].
\DIt returns a match if the string doesn't contain the digits [0-9].
\sIt returns a match if the string contains any white space character.
\SIt returns a match if the string doesn't contain any white space character.
\wIt returns a match if the string contains any word characters.
\WIt returns a match if the string doesn't contain any word.
\ZReturns a match if the specified characters are at the end of the string.

Sets

A set is a group of characters given inside a pair of square brackets. It represents the special meaning.
SNSetDescription
1[arn]Returns a match if the string contains any of the specified characters in the set.
2[a-n]Returns a match if the string contains any of the characters between a to n.
3[^arn]Returns a match if the string contains the characters except a, r, and n.
4[0123]Returns a match if the string contains any of the specified digits.
5[0-9]Returns a match if the string contains any digit between 0 and 9.
6[0-5][0-9]Returns a match if the string contains any digit between 00 and 59.
10[a-zA-Z]Returns a match if the string contains any alphabet (lower-case or upper-case).

The Match object methods

There are the following methods associated with the Match object.
  1. span(): It returns the tuple containing the starting and end position of the match.
  2. string(): It returns a string passed into the function.
  3. group(): The part of the string is returned where the match is found.

Example

  1. import re  
  2.   
  3. str = "How are you. How is everything"  
  4.   
  5. matches = re.search("How", str)  
  6.   
  7. print(matches.span())  
  8.   
  9. print(matches.group())  
  10.   
  11. print(matches.string)  
Output:
(0, 3)
How
How are you. How is everything

Comments

Popular posts from this blog

Python File Handling & Exception Handling

Introduction to Python & its Data types

Python List, Tuple and Dictionary