0% found this document useful (0 votes)
12 views

Python - Slide 5

Advanced Topics in Python

Uploaded by

aditya.2352700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python - Slide 5

Advanced Topics in Python

Uploaded by

aditya.2352700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Problem Solving using Python

Packages & Modules


By: Dr Aditya Saxena
Packages and Modules

In Python, both modules and packages organize and structure the
code.
In simple terms, a Module is a single file containing python code,
whereas
a Package is a collection of modules that are organized in a directory
hierarchy.
Modules
o A module is a single file containing Python definitions and statements.

o These definitions and statements can include variables, functions, and classes
and can be used to organize related functionality into a single, reusable package.

o Modules can be imported and used in other Python files using the import
statement.

o Some popular inbuilt modules in Python are math, random, csv, and datetime.
Module Example:

demo.py

Calc.py
Module Example:

demo.py

Calc.py
Module Example:

demo.py

Calc.py
Packages (folder/directory)
o Python Packages are collections of modules that provide a set of related
functionalities, and these modules are organized in a directory hierarchy.

o In simple terms, packages in Python are a way of organizing related modules.

o Each Python package must contain a file named _init_.py.


Problem Solving using Python
File Handling
By: Dr Aditya Saxena
File
Handling
File is a named location
on disk to store related
information permanently

New
Folder

abc.txt

D:\New folder\
abc.txt
Steps in File Handling
Open the file

Perform the
read or write
operation

Close the file


Step 1. open the file
• Before you can read or write a file, you have to
open it using Python's built-in open() function.
• This function returns a file object
• If the file cannot be opened, an Error is raised

File_object = open( file_name ,


[access_mode] )

A string value that


contains the
absolute / relative
path the file
Step 1. open the file
• Before you can read or write a file, you have to
open it using Python's built-in open() function.
• This function returns a file object
• Ifthe file cannot be opened, an Error is raised

File_object = open( file_name,


[access_mode] )

the mode in which


the file has to be
opened, i.e., read,
write, append
Access modes of a file
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
open for writing, appending to the end of
'a'
the file- if it exists
'+' open for updating (reading andwriting)
To open a
file
# open file in current directory
>>> f =open("test.txt")

Relative Path

Absolute Path
# specifying full path
>>> f =
open("C:/Python3/README.txt")
Step 2. Writing in Files
write()
• The write() method writes any string to an open file.
• returns the number of characters written.
Syntax
fileObj.write(string)

string to be written
into the opened
file
write
()
>>>a=open("abc.txt","w")
>>>a.write("""Hi \nWelcome to
Introduction to Python Class""")
43
>>>a.close()

abc.tx
t
Reading from
files
read( returns the read
) string
>>>fileObj.read([co
Syntax
unt])
the number of
starts reading from
bytes to be read /
the beginning of
if not given then
the file
reads the complete
file
Reading from
files
>>>a=open("abc.tx
t","r")
>>>a.read(10)
'Hi\ nWelcome‘
>>>a.close()
Reading from
files
>>>a=open("abc.txt","r")
>>>a.read() ## return string

'Hi\nWelcome to\nIntroduction to Python


Class‘
>>>a.close()

<Subject Code> <Name of 3


Subject> 8
Reading from
files
readlines() read all the lines of a file
in a list
>>>a=open("abc.txt","r")
>>>a.readlines() ## return list
of string
['Hi\n', 'Welcome to\n', 'Introduction to
Python Class']
>>>a.close()
Reading from
files
• We can read a file line-by-line using a
for loop.
• This is both efficient and fast.
>>>a=open("abc.txt","r")
>>>for line in a:
print(line)
Two new lines -
one due to actual
line-break and
Hi
another due to
print function
Welcome to

Introduction to PythonClass
Reading from
files
readline() read one line each time from the file, including the newline character.
>>>a = open("abc.txt","r")
>>>a.readline()
'Hi\n‘
>>>a.readline()
'Welcome to\n‘
>>>a.readline()
'Introduction to
PythonClass‘
>>>a.readline()
‘’
>>>a.close()
Step 3. Closing the file
• It flushes any unwritten information and closes the
file object, after which no more writingcan be
done.
• Python automatically closes a file when the
reference object of a file is reassigned to
anotherfile.
• It is a good practice to use the close() method to
close a file.

>>>fileObject.close()
What is regular expression?
• The term "regular expression", sometimes also
called regex
• Regular Expressions are used in programming
languages to filter texts or strings.
• It's possible to check - if a text or a string
matches a regular expression.
Problem Solving using Python
Regular Expressions
By: Dr Aditya Saxena
• In Python, we have module “re” that helps with regular
expressions.
• So you need to import library re before you can use
regular expressions in Python.

import re
What are various methods of Regular
Expressions?
The ‘re’ package provides multiple methods to perform queries on an
input string.
• re.match()
• re.search()
• re.findall()
re.match(pattern, string):
• The match() method will only find matches if they occur at the start of the string being
searched.
• For example, calling match() on the string ‘AV Analytics AV’ and looking for a pattern ‘AV’ will
match.
• However, if we look for only Analytics, the pattern will not match.
Code
>>> import re
>>> result = re.match(r'AV', 'AV Analytics Vidhya AV')
>>> result
<re.Match object; span=(0, 2), match='AV'>
>>> result.start()
0
>>> result.end()
2
>>> result.group(0)
'AV'
re.search(pattern, string)
• It is similar to match() but it doesn’t restrict us to find matches at the beginning of the
string only.
• Unlike previous method, here searching for pattern ‘Analytics’ will return a match.
Code
• result = re.search(r'Analytics', 'AV Analytics Vidhya AV')
• print (result.group(0))
Output: Analytics

Here you can see that, search() method is able to find a pattern from any position of
the string but it only returns the first occurrence of the search pattern.
re.findall (pattern, string):
• It helps to get a list of all matching patterns.
• It has no constraints of searching from start or end.
• If we will use method findall to search ‘AV’ in given string it will return both
occurrence of AV.
• re.findall() it can work like re.search() and re.match() both.
result = re.findall('AV', 'AV Analytics Vidhya AV')
• print (result)
Output: ['AV', 'AV']
re.compile(pattern, repl, string)
• We can combine a regular expression pattern into
pattern objects, which can be used for pattern
matching.
• It also helps to search a pattern again without rewriting
it.
Code
• pattern=re.compile('AV')
• result=pattern.findall('AV Analytics Vidhya AV')
• print (result)
• ['AV', 'AV']
• result2=pattern.findall('AV is largest analytics community of India')
• print (result2)
• ['AV']
• Regular expressions use two types of characters:

a)Meta characters: these characters have a special meaning, Ex. .


^ $ * + ? {}[]\|()
b) Literals: have usual meaning
Ex. A, B, a,b,text,1,2…….
The following special-character sequences are recognized in regular expression
patterns:
Character Description
. Matches any character except newline.
^ Matches the start of a string.
$ Matches the end of a string.
The following special-character sequences are recognized in regular expression
patterns:

Character Description

* Matches zero or more repetitions of the preceding (before)


expression, matching as many repetitions as possible.
+ Matches one or more repetitions of the preceding expression,
matching as many repetitions as possible.
Difference between * and +
+ Matches one or more repetitions of the preceding expression,
* Matches zero or more repetitions of the preceding (before)
matching as many repetitions as possible.
expression, matching as many repetitions as possible.
raw
*? Matches zero or more repetitions of the preceding expression, matching as few
repetitions as possible.
? Matches zero or one repetition of the preceding expression.

neither 0 nor 1 repetitions so no match


{m} Matches exactly m repetitions of the preceding expression.

{m, n} Matches from m to n repetitions of the preceding expression, matching as many


repetitions as possible. If m is omitted, it defaults to 0. If n is omitted, it defaults to infinity.

Exactly 2 repetitions of 'l'

From 0 to 2 repetitions of 'l'


Predefined Character Classes
• \d Matches any decimal digit; equivalent to the set [0-9].
• \D The complement of \d. It matches any non-digit character;
equivalent to the set [^0-9].
• \w Matches any alphanumeric character; equivalent to [a-zA-
Z0-9_].
• \W Matches the complement of \w.
[ ] - Square brackets

Square brackets specifies a set of characters we wish to match.

Expression String Matched ?

a 1 match

ac 2 matches
[abc]
Hey Jude No match

abc de ca 5 matches

Here, [abc] will match if the string we are trying to match contains any of the a, b or c.
We can also specify a range of characters using - inside square brackets.

•[a-e] is the same as [abcde].

•[1-4] is the same as [1234].

•[0-39] is the same as [01239].

We can complement (invert) the character set by using caret ^ symbol at the start

of a square-bracket.

•[^abc] means any character except a or b or c.

•[^0-9] means any non-digit character.


Problem: Validate a phone number (phone number must be
of 10 digits and starts with 8 or 9)

• We have a list phone numbers in list “li” and


here we will validate phone numbers using
regular
Solution
• import re
• li=['9999999999','999999-
999','99999x9999']
• for val in li:
if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
print ('yes' )
else:
print (‘No' )

You might also like