SlideShare a Scribd company logo
1 of 40
Swarup Kr Ghosh
MIS Group
IIM Calcutta
swarupg1@gmail.com
 Regular Expression
 File Input/output
 Operating System
 Time
7/21/2017Swarup Kr Ghosh 2
 Special sequence of characters that helps ‘match’ or
‘find’ ‘other strings or sets of strings’
 Regular expressions are widely used in UNIX world
 The module ‘re’ provides full support for Perl-like
regular expressions in Python
 The re module raises the exception ‘re.error’ if an error
occurs while compiling or using a regular expression
7/21/2017Swarup Kr Ghosh 3
 This function attempts to match RE pattern to string with
optional flags
Syntax: re.match(pattern, string, flags=0)
7/21/2017Swarup Kr Ghosh 4
 The re.match() returns a match object on success,
None on failure
 We would use group(num) or groups() of match
object to get matched expression
7/21/2017Swarup Kr Ghosh 5
7/21/2017Swarup Kr Ghosh 6
import re
Match= re.search(‘iig’,’called piiig’)
Match.group() #or match
‘iig’
import re
Match= re.search(‘igs’,’called piiig’)
Match.group() #or match
‘None type object has no attribute group’
7/21/2017Swarup Kr Ghosh 7
import re
>>> line="Cats are smarter than dogs"
>>> matchObj=re.match(r'(.*) are (.*?) .*',line, re.M|re.I)
>>> if matchObj:
print("matchObj.group() :",matchObj.group())
print("matchObj.group(1) :",matchObj.group(1))
print("matchObj.group(2) :",matchObj.group(2))
else:
print("No match!!")
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
7/21/2017Swarup Kr Ghosh 8
 This function searches for first occurrence of RE pattern
within string with optional flags
 Syntax: re.search(pattern, string, flags=0)
7/21/2017Swarup Kr Ghosh 9
 The re.search() returns a match object on success,
None on failure
 We would use group(num) or groups() function of match
object to get matched expression
7/21/2017Swarup Kr Ghosh 10
>>> import re
>>> line="Cats are smarter than dogs"
>>> matchObj=re.search(r'(.*) are (.*?) .*',line, re.M|re.I)
>>> if matchObj:
print("matchObj.group() :",matchObj.group())
print("matchObj.group(1) :",matchObj.group(1))
print("matchObj.group(2) :",matchObj.group(2))
else:
print("No match!!")
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
7/21/2017Swarup Kr Ghosh 11
 Python offers two different primitive operations
based on regular expressions:
 match() checks for a match only at the beginning
of the string
 search() checks for a match anywhere in the string
7/21/2017Swarup Kr Ghosh 12
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print ("match --> matchObj.group() : ", matchObj.group() )
else:
print ("No match!!“)
matchObj = re.search( r'dogs', line, re.M|re.I)
if matchObj:
print ("search --> matchObj.group() : ", matchObj.group())
else:
print ("Not found!!“)
No match!!
search --> matchObj.group() : dogs
7/21/2017Swarup Kr Ghosh 13
 find() determines if string str occurs in string, or in a
substring of string if starting index beg and ending
index end are given
 Syntax: str.find(str, beg=0 end=len(string))
def Find(pat,text):
match=re.search('pat','text')
if match:
print(match.group())
else:
print("Not Found")
7/21/2017Swarup Kr Ghosh 14
>>> import re
>>> def find(pat,text):
match=re.search(pat,text)
if match:
print(match.group())
else:
print("Not Found")
>>> find('iiig','called piiig')
iiig
>>> find('ig','called piiig')
ig
>>> find('igs','called piiig')
Not Found
7/21/2017Swarup Kr Ghosh 15
 Any special character written as . or *
.(dot) any character
w  word character
d  digit
s white space
S  non white space
7/21/2017Swarup Kr Ghosh 16
>>> find(':www','c.lled:cat much better:xyz')
:cat
>>> find(':ddd','c.lled:cat123xyz')
Not Found
>>> find('ddd','c.lled:cat123xyz')
123
>>> find(':ddd','c.lled:cat:123xyz')
:123
>>> find('ds+ds+d','1 2 3')
1 2 3
>>> find(':w+s+w+','c.iied :cat123xyz better :xyz')
:cat123xyz better
>>> find(':.+','c.iied :cat123xyz better :xyz')
:cat123xyz better :xyz
>>> find('[w.]+@[w.]+','blah nick.p@gmail.com yahoo@')
nick.p@gmail.com
>>> find('w+@w+','blah nick.p@gmail.com yahoo@')
p@gmail
>>> m=re.search('[w.]+@[w.]+','blah nick.p@gmail.com yahoo@')
>>> m
<_sre.SRE_Match object; span=(5, 21), match='nick.p@gmail.com'>
>>> m.group()
'nick.p@gmail.com'
7/21/2017Swarup Kr Ghosh 17
re.findall('[w.]+@[w.]+','blah nick.p@gmail.com yahoo@in')
['nick.p@gmail.com', 'yahoo@in']
re.findall('([w.]+)@([w.]+)','blah nick.p@gmail.com yahoo@in')
[('nick.p', 'gmail.com'), ('yahoo', 'in')]
7/21/2017Swarup Kr Ghosh 18
 replace() method replaces all occurrences of the
RE pattern in string with repl, substituting all
occurrences unless max provided
 This method would return modified string
 Syntax:
◦ str.replace(old, new[, max])
◦ re.sub(pattern, repl, string, max=0)
7/21/2017Swarup Kr Ghosh 19
import re
phone = "2004-959-559 “ #This is Phone Number
num = re.sub(r'#.*$', "", phone) #Delete comments
print ("Phone Num : ", num)
#Remove anything other than digits
num = re.sub(r'D', "", phone)
print "Phone Num : ", num
Phone Num : 2004-959-559
Phone Num : 2004959559
str = "this is string example....wow!!! this is really string"
print(str.replace("is", "was"))
print(str.replace("is", "was", 3))
thwas was string example....wow!!! thwas was really string thwas
was string example....wow!!! thwas is really string
7/21/2017Swarup Kr Ghosh 20
 Reading Keyboard Input:
 raw_input()
◦ reads one line from standard input and returns it as a
string (removing the trailing newline)
 input()
◦ equivalent to raw_input, except that it assumes the input
is a valid Python expression and returns the evaluated
result to you
7/21/2017Swarup Kr Ghosh 21
raw_input():
str = raw_input("Enter your input: ")
Print("Received input is : ", str)
Enter your input: Hello Python
Received input is : Hello Python
input():
str = input("Enter your input: ")
print ("Received input is : ", str)
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 50, 10]
7/21/2017Swarup Kr Ghosh 22
 Syntax:
file object = open(file_name [, access_mode][, buffering])
 file_name: The file_name argument is a string value that
contains the name of the file
 access_mode: The access_mode determines the mode in
which the file has to be opened, i.e., read, write, append
 buffering: If the buffering value is set to 0, no buffering, if the
buffering value is 1, line buffering, if you specify the buffering
value as an integer greater than 1, then buffering action will
be performed with the indicated buffer size
7/21/2017Swarup Kr Ghosh 23
Modes Descriptions
R Opens file readonly
Rb Reading in binary format
r+ Both reading and writing
rb+ Both reading and writing in bianry format
W Write only (if file does not exist, create a new file for writing)
Wb Write only in binary format (if file does not exist, create)
w+ Both writing and reading
wb+ Both writing and reading in binary format
A Open a file for appending (if file does not exist, create)
Ab Appending in binary format
a+ Both appending and reading
ab+ Both appending and reading in binary format
7/21/2017Swarup Kr Ghosh 24
 file.closed():
◦ Return true if file is closed, false otherwise
 file.mode():
◦ Return access mode with which file was opened
 file.name():
◦ Returns name of file
 file.softspace():
◦ Return false if space explicity required with print, true
otherwise
7/21/2017Swarup Kr Ghosh 25
 filename.close():
◦ ---to close a file
 filename.read():
◦ ---to read a file
 filename.write():
◦ ---to write a file
7/21/2017Swarup Kr Ghosh 26
f= open(“wavelet.txt”,’w’)
f.close()
print(“Name of file:”,f.name)
print(“Closed or not:”,f.close)
print(“Opening mode:”,f.mode)
Name of file: wavelet2.txt
Closed or not: true
Opening mode: w
7/21/2017Swarup Kr Ghosh 27
f= open(“wavelet2.txt”, ‘w’)
f.write(“Python is a great programming language”)
f.close()
o/p:
The message have been written in wavelet2.txt
f= open(“wavelet2.txt”, ‘r’)
strf=f.read(10)
f.close()
o/p:
1st ten characters of the file wavelet2.txt
7/21/2017Swarup Kr Ghosh 28
 filename.read():
◦ ---show whole file
 filename.readline():
◦ ---show first line of the file
7/21/2017Swarup Kr Ghosh 29
def cat(file name):
f= open(filename, ‘r’)
for line in f:
print(line)
return
def cat(file name):
f= open(filename, ‘r’)
lines=f.read()
return
def cat(file name):
f= open(filename, ‘r’)
f.readline()
return
7/21/2017Swarup Kr Ghosh 30
# Read a basic CSV file
f = open(“scmods.csv”,”rb”)
for r in csv.reader(f):
print (r)
# Write a basic CSV file
data = [
[‘Blues’,’Elwood’,’1060 W Addison’,’Chicago’,’IL’,’60613’ ],
[‘McGurn’,’Jack’,’4802 N Broadway’,’Chicago’,’IL’,’60640’ ],
]
f = open(“address.csv”,”wb”)
w = csv.writer(f)
w.writerows(data)
f.close()
7/21/2017Swarup Kr Ghosh 31
 Python os module provides methods that help you
perform file-processing operations, such as
renaming and deleting files
 rename()
◦ Syntax:
◦ os.rename(current_file_name, new_file_name)
 remove():
◦ Syntax:
◦ os.remove(file_name)
7/21/2017Swarup Kr Ghosh 32
import os
os.rename(test1.txt,test2.txt)
Os.remove(test2.txt)
7/21/2017Swarup Kr Ghosh 33
import os
os.mkdir(“test”) #create a directory
os.chdir(“c:python34Tools”) #change directory
os.getcwd() #location of current directory
os.rmdir(“test”) #remove directory
7/21/2017Swarup Kr Ghosh 34
import os
f=open("wavelet1.txt",'r')
str1=f.read() #read whole file
print("read string is:",str1)
f.close()
print("Name of file:",f.name)
print("closed or not:",f.closed)
print("opening mode:",f.mode)
print(str1) #print whole file
7/21/2017Swarup Kr Ghosh 35
import os
f=open("wavelet1.txt",'r')
print("name of the file:",f.name)
for index in range(5):
line=f.next()
print("Line No %d - %s",%(index,line))
f.close()
o/p:
Line No 0 – This is the 1st line
Line No 1 – This is the 2nd line
………
7/21/2017Swarup Kr Ghosh 36
>>> import time
>>> ticks=time.time()
>>> print("no of ticks since 12:00am,jan 1, 1970:",ticks)
no of ticks since 12:00am,jan 1, 1970: 1428682716.747197
#To get local current time:
>>> import time
>>> localtime=time.localtime(time.time())
>>> print("Local current time:",localtime)
Local current time: time.struct_time(tm_year=2015,
tm_mon=4, tm_mday=10, tm_hour=21, tm_min=53,
tm_sec=37, tm_wday=4, tm_yday=100, tm_isdst=0)
7/21/2017Swarup Kr Ghosh 37
 Python CGI programming
 Python Database access
 Python Networking
 Python XML processing
 Python GUI programming
7/21/2017Swarup Kr Ghosh 38
#!/usr/bin/env python
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1,
facecolor='green',
alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$mathrm{Histogram of IQ:} mu=100,
sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
7/21/2017Swarup Kr Ghosh 39
7/21/2017Swarup Kr Ghosh 40

More Related Content

What's hot

Rust-lang
Rust-langRust-lang
Optimizing Tcl Bytecode
Optimizing Tcl BytecodeOptimizing Tcl Bytecode
Optimizing Tcl Bytecode
Donal Fellows
 

What's hot (20)

Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
360|iDev
360|iDev360|iDev
360|iDev
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Workshop on command line tools - day 1
Workshop on command line tools - day 1Workshop on command line tools - day 1
Workshop on command line tools - day 1
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Groovy!
Groovy!Groovy!
Groovy!
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
Beyond javascript using the features of tomorrow
Beyond javascript   using the features of tomorrowBeyond javascript   using the features of tomorrow
Beyond javascript using the features of tomorrow
 
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant) Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
 
Optimizing Tcl Bytecode
Optimizing Tcl BytecodeOptimizing Tcl Bytecode
Optimizing Tcl Bytecode
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Леонид Шевцов «Clojure в деле»
Леонид Шевцов «Clojure в деле»Леонид Шевцов «Clojure в деле»
Леонид Шевцов «Clojure в деле»
 

Similar to Python lec5

How to write rust instead of c and get away with it
How to write rust instead of c and get away with itHow to write rust instead of c and get away with it
How to write rust instead of c and get away with it
Flavien Raynaud
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
agnonchik
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
findextensions(2).py#!usrlocalbinpython3import sysim.docx
findextensions(2).py#!usrlocalbinpython3import sysim.docxfindextensions(2).py#!usrlocalbinpython3import sysim.docx
findextensions(2).py#!usrlocalbinpython3import sysim.docx
AKHIL969626
 

Similar to Python lec5 (20)

Python lec3
Python lec3Python lec3
Python lec3
 
Python basic
Python basicPython basic
Python basic
 
Assignment6
Assignment6Assignment6
Assignment6
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
How to write rust instead of c and get away with it
How to write rust instead of c and get away with itHow to write rust instead of c and get away with it
How to write rust instead of c and get away with it
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Jug java7
Jug java7Jug java7
Jug java7
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
findextensions(2).py#!usrlocalbinpython3import sysim.docx
findextensions(2).py#!usrlocalbinpython3import sysim.docxfindextensions(2).py#!usrlocalbinpython3import sysim.docx
findextensions(2).py#!usrlocalbinpython3import sysim.docx
 
CommonJS: JavaScript Everywhere
CommonJS: JavaScript EverywhereCommonJS: JavaScript Everywhere
CommonJS: JavaScript Everywhere
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Recently uploaded (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 

Python lec5

  • 1. Swarup Kr Ghosh MIS Group IIM Calcutta swarupg1@gmail.com
  • 2.  Regular Expression  File Input/output  Operating System  Time 7/21/2017Swarup Kr Ghosh 2
  • 3.  Special sequence of characters that helps ‘match’ or ‘find’ ‘other strings or sets of strings’  Regular expressions are widely used in UNIX world  The module ‘re’ provides full support for Perl-like regular expressions in Python  The re module raises the exception ‘re.error’ if an error occurs while compiling or using a regular expression 7/21/2017Swarup Kr Ghosh 3
  • 4.  This function attempts to match RE pattern to string with optional flags Syntax: re.match(pattern, string, flags=0) 7/21/2017Swarup Kr Ghosh 4
  • 5.  The re.match() returns a match object on success, None on failure  We would use group(num) or groups() of match object to get matched expression 7/21/2017Swarup Kr Ghosh 5
  • 7. import re Match= re.search(‘iig’,’called piiig’) Match.group() #or match ‘iig’ import re Match= re.search(‘igs’,’called piiig’) Match.group() #or match ‘None type object has no attribute group’ 7/21/2017Swarup Kr Ghosh 7
  • 8. import re >>> line="Cats are smarter than dogs" >>> matchObj=re.match(r'(.*) are (.*?) .*',line, re.M|re.I) >>> if matchObj: print("matchObj.group() :",matchObj.group()) print("matchObj.group(1) :",matchObj.group(1)) print("matchObj.group(2) :",matchObj.group(2)) else: print("No match!!") matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter 7/21/2017Swarup Kr Ghosh 8
  • 9.  This function searches for first occurrence of RE pattern within string with optional flags  Syntax: re.search(pattern, string, flags=0) 7/21/2017Swarup Kr Ghosh 9
  • 10.  The re.search() returns a match object on success, None on failure  We would use group(num) or groups() function of match object to get matched expression 7/21/2017Swarup Kr Ghosh 10
  • 11. >>> import re >>> line="Cats are smarter than dogs" >>> matchObj=re.search(r'(.*) are (.*?) .*',line, re.M|re.I) >>> if matchObj: print("matchObj.group() :",matchObj.group()) print("matchObj.group(1) :",matchObj.group(1)) print("matchObj.group(2) :",matchObj.group(2)) else: print("No match!!") matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter 7/21/2017Swarup Kr Ghosh 11
  • 12.  Python offers two different primitive operations based on regular expressions:  match() checks for a match only at the beginning of the string  search() checks for a match anywhere in the string 7/21/2017Swarup Kr Ghosh 12
  • 13. import re line = "Cats are smarter than dogs"; matchObj = re.match( r'dogs', line, re.M|re.I) if matchObj: print ("match --> matchObj.group() : ", matchObj.group() ) else: print ("No match!!“) matchObj = re.search( r'dogs', line, re.M|re.I) if matchObj: print ("search --> matchObj.group() : ", matchObj.group()) else: print ("Not found!!“) No match!! search --> matchObj.group() : dogs 7/21/2017Swarup Kr Ghosh 13
  • 14.  find() determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given  Syntax: str.find(str, beg=0 end=len(string)) def Find(pat,text): match=re.search('pat','text') if match: print(match.group()) else: print("Not Found") 7/21/2017Swarup Kr Ghosh 14
  • 15. >>> import re >>> def find(pat,text): match=re.search(pat,text) if match: print(match.group()) else: print("Not Found") >>> find('iiig','called piiig') iiig >>> find('ig','called piiig') ig >>> find('igs','called piiig') Not Found 7/21/2017Swarup Kr Ghosh 15
  • 16.  Any special character written as . or * .(dot) any character w  word character d  digit s white space S  non white space 7/21/2017Swarup Kr Ghosh 16
  • 17. >>> find(':www','c.lled:cat much better:xyz') :cat >>> find(':ddd','c.lled:cat123xyz') Not Found >>> find('ddd','c.lled:cat123xyz') 123 >>> find(':ddd','c.lled:cat:123xyz') :123 >>> find('ds+ds+d','1 2 3') 1 2 3 >>> find(':w+s+w+','c.iied :cat123xyz better :xyz') :cat123xyz better >>> find(':.+','c.iied :cat123xyz better :xyz') :cat123xyz better :xyz >>> find('[w.]+@[w.]+','blah nick.p@gmail.com yahoo@') nick.p@gmail.com >>> find('w+@w+','blah nick.p@gmail.com yahoo@') p@gmail >>> m=re.search('[w.]+@[w.]+','blah nick.p@gmail.com yahoo@') >>> m <_sre.SRE_Match object; span=(5, 21), match='nick.p@gmail.com'> >>> m.group() 'nick.p@gmail.com' 7/21/2017Swarup Kr Ghosh 17
  • 18. re.findall('[w.]+@[w.]+','blah nick.p@gmail.com yahoo@in') ['nick.p@gmail.com', 'yahoo@in'] re.findall('([w.]+)@([w.]+)','blah nick.p@gmail.com yahoo@in') [('nick.p', 'gmail.com'), ('yahoo', 'in')] 7/21/2017Swarup Kr Ghosh 18
  • 19.  replace() method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided  This method would return modified string  Syntax: ◦ str.replace(old, new[, max]) ◦ re.sub(pattern, repl, string, max=0) 7/21/2017Swarup Kr Ghosh 19
  • 20. import re phone = "2004-959-559 “ #This is Phone Number num = re.sub(r'#.*$', "", phone) #Delete comments print ("Phone Num : ", num) #Remove anything other than digits num = re.sub(r'D', "", phone) print "Phone Num : ", num Phone Num : 2004-959-559 Phone Num : 2004959559 str = "this is string example....wow!!! this is really string" print(str.replace("is", "was")) print(str.replace("is", "was", 3)) thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string 7/21/2017Swarup Kr Ghosh 20
  • 21.  Reading Keyboard Input:  raw_input() ◦ reads one line from standard input and returns it as a string (removing the trailing newline)  input() ◦ equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you 7/21/2017Swarup Kr Ghosh 21
  • 22. raw_input(): str = raw_input("Enter your input: ") Print("Received input is : ", str) Enter your input: Hello Python Received input is : Hello Python input(): str = input("Enter your input: ") print ("Received input is : ", str) Enter your input: [x*5 for x in range(2,10,2)] Recieved input is : [10, 50, 10] 7/21/2017Swarup Kr Ghosh 22
  • 23.  Syntax: file object = open(file_name [, access_mode][, buffering])  file_name: The file_name argument is a string value that contains the name of the file  access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append  buffering: If the buffering value is set to 0, no buffering, if the buffering value is 1, line buffering, if you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size 7/21/2017Swarup Kr Ghosh 23
  • 24. Modes Descriptions R Opens file readonly Rb Reading in binary format r+ Both reading and writing rb+ Both reading and writing in bianry format W Write only (if file does not exist, create a new file for writing) Wb Write only in binary format (if file does not exist, create) w+ Both writing and reading wb+ Both writing and reading in binary format A Open a file for appending (if file does not exist, create) Ab Appending in binary format a+ Both appending and reading ab+ Both appending and reading in binary format 7/21/2017Swarup Kr Ghosh 24
  • 25.  file.closed(): ◦ Return true if file is closed, false otherwise  file.mode(): ◦ Return access mode with which file was opened  file.name(): ◦ Returns name of file  file.softspace(): ◦ Return false if space explicity required with print, true otherwise 7/21/2017Swarup Kr Ghosh 25
  • 26.  filename.close(): ◦ ---to close a file  filename.read(): ◦ ---to read a file  filename.write(): ◦ ---to write a file 7/21/2017Swarup Kr Ghosh 26
  • 27. f= open(“wavelet.txt”,’w’) f.close() print(“Name of file:”,f.name) print(“Closed or not:”,f.close) print(“Opening mode:”,f.mode) Name of file: wavelet2.txt Closed or not: true Opening mode: w 7/21/2017Swarup Kr Ghosh 27
  • 28. f= open(“wavelet2.txt”, ‘w’) f.write(“Python is a great programming language”) f.close() o/p: The message have been written in wavelet2.txt f= open(“wavelet2.txt”, ‘r’) strf=f.read(10) f.close() o/p: 1st ten characters of the file wavelet2.txt 7/21/2017Swarup Kr Ghosh 28
  • 29.  filename.read(): ◦ ---show whole file  filename.readline(): ◦ ---show first line of the file 7/21/2017Swarup Kr Ghosh 29
  • 30. def cat(file name): f= open(filename, ‘r’) for line in f: print(line) return def cat(file name): f= open(filename, ‘r’) lines=f.read() return def cat(file name): f= open(filename, ‘r’) f.readline() return 7/21/2017Swarup Kr Ghosh 30
  • 31. # Read a basic CSV file f = open(“scmods.csv”,”rb”) for r in csv.reader(f): print (r) # Write a basic CSV file data = [ [‘Blues’,’Elwood’,’1060 W Addison’,’Chicago’,’IL’,’60613’ ], [‘McGurn’,’Jack’,’4802 N Broadway’,’Chicago’,’IL’,’60640’ ], ] f = open(“address.csv”,”wb”) w = csv.writer(f) w.writerows(data) f.close() 7/21/2017Swarup Kr Ghosh 31
  • 32.  Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files  rename() ◦ Syntax: ◦ os.rename(current_file_name, new_file_name)  remove(): ◦ Syntax: ◦ os.remove(file_name) 7/21/2017Swarup Kr Ghosh 32
  • 34. import os os.mkdir(“test”) #create a directory os.chdir(“c:python34Tools”) #change directory os.getcwd() #location of current directory os.rmdir(“test”) #remove directory 7/21/2017Swarup Kr Ghosh 34
  • 35. import os f=open("wavelet1.txt",'r') str1=f.read() #read whole file print("read string is:",str1) f.close() print("Name of file:",f.name) print("closed or not:",f.closed) print("opening mode:",f.mode) print(str1) #print whole file 7/21/2017Swarup Kr Ghosh 35
  • 36. import os f=open("wavelet1.txt",'r') print("name of the file:",f.name) for index in range(5): line=f.next() print("Line No %d - %s",%(index,line)) f.close() o/p: Line No 0 – This is the 1st line Line No 1 – This is the 2nd line ……… 7/21/2017Swarup Kr Ghosh 36
  • 37. >>> import time >>> ticks=time.time() >>> print("no of ticks since 12:00am,jan 1, 1970:",ticks) no of ticks since 12:00am,jan 1, 1970: 1428682716.747197 #To get local current time: >>> import time >>> localtime=time.localtime(time.time()) >>> print("Local current time:",localtime) Local current time: time.struct_time(tm_year=2015, tm_mon=4, tm_mday=10, tm_hour=21, tm_min=53, tm_sec=37, tm_wday=4, tm_yday=100, tm_isdst=0) 7/21/2017Swarup Kr Ghosh 37
  • 38.  Python CGI programming  Python Database access  Python Networking  Python XML processing  Python GUI programming 7/21/2017Swarup Kr Ghosh 38
  • 39. #!/usr/bin/env python import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt mu, sigma = 100, 15 x = mu + sigma*np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75) # add a 'best fit' line y = mlab.normpdf( bins, mu, sigma) l = plt.plot(bins, y, 'r--', linewidth=1) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title(r'$mathrm{Histogram of IQ:} mu=100, sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() 7/21/2017Swarup Kr Ghosh 39