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
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
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
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