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

Practical11 Python Programming CkC21BUjW7

5

Uploaded by

sagargurav1812
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Practical11 Python Programming CkC21BUjW7

5

Uploaded by

sagargurav1812
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

SVKM’s NMIMS University

Mukesh Patel School of Technology Management & Engineering/ School of Technology


Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

PRACTICAL 11
Part A (To be referred by students)

Regular Expression and SQLite

SAVE THE FILE AND UPLOAD AS (RollNo_Name_Exp11)


Problem Statement:
Apply core and object-oriented Python concepts to build following applications

Topic covered: regular expression and database connectivity through sqlite

Learning Objective: Learner would be able to


1. Work with regular expressions
2. Connect python program to sqlite
3. Perform CRUD operations

Theory:

Regular Expression:-
- RE are noting but strings continuing characters and special symbols.
- Also called regex
- Python provides re module for RE
- This module contains methods like
o compile()
o search()
o match()
o findall()
o split()
o sub()
etc
- Example:-
import re
reg=r'm\w\w' # r is used to represented, it is raw string.
print(reg)
o m – represents the words starting with ‘m’ should be matched
o w – represents any one character in a-a or A-Z or 0-9

1|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

- Generally we write RE as raw string.


- Example on String and RE:-
import re
str="this is \n RE"
print(str)
RE=r'this is \n RE'
print(RE)

- reg=r'm\w\w' # r is used to represented, it is raw string.


- reg=r'm\\w\\w' # r is used to represent, it is string.

compile( ) method of re
- it’s a step after creating RE. Compile RE.
search( ) and match( )
- its step after compilation to run expression on string.
group( )
- it’s a method to access string return by search( ) or match( )

Programming example to create RE and access it.


import re
prog=re.compile(r'm\w\w') // compile( ) returns the RE
str=r'cat mat bat rat moon man'
result=prog.search(str)
print(result.group())
When we want to use same expression on different string we can compile it once and use
multiple time.
import re
prog=re.compile(r'm\w\w')
str='cat mat bat rat moon man'
result=prog.search(str)
print(result.group())

str1='systematic'
result=prog.search(str1)
print(result.group())

Single Step to compile and run RE


prog=re.compile(r'm\w\w') Result=re.search(r‘m\w\w’,str)
str='cat mat bat rat moon man'
result=prog.search(str)

2|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

General form of writing RE as:-


Result=re.search(‘expression’, ‘string’)
- If regular expression is not present in given string search returns None.
Example:-
import re
prog=re.compile(r'm\w\w')
str='cat mat bat rat moon man'
result=prog.search(str)
print(result.group())

str1='system'
result=prog.search(str1)
if result:
print(result.group( ))
findall( )
- This method returns all resultant string into a list.
Example:-
import re
prog=re.compile(r'm\w\w')
str='cat mat bat rat moon man'
result=prog.findall(str)
print(result)
match( )
- It returns the resultant string only if it is found in beginning of the string.
- The match( ) functions returns None if the string is not in the beginning.

Python program to create a RE using the match ( ) method to search for strings starting
with m and having total 3 characters.
Program 1:-
import re
str='man ran maaa'
result=re.match(r'm\w\w',str)
print(result.group())

Program 2:-
import re
str='ran maaa'
result=re.match(r'm\w\w',str)
print(result)

split( )
- To split the string into pieces according to RE and returns the pieces as elements of a
list.
- Example:=

3|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

re.split(r‘\W+’,str)
o w – Represents alphanumeric characters.
o W – Represents any character that is not alphanumeric.
 + after W represents to match 1 or more occurrences indicated by W.

import re
str='This; is the: "core" python\'s book'
result=re.split(r'\W+',str)
print(result)

output:-
['This', 'is', 'the', 'core', 'python', 's', 'book']

sub( )
- Finds a string and replace it with a new string.
- Format of the method is:
re.sub(RE, new string, string)
- Example:-
re.sub(r‘Mumbai’, ‘Shirpur’, str)

RE are used to perform following operations:-


- Matching String
- Searching for String
- Finding for all Strings
- Splitting a string into pieces
Sequence Characters in RE
- Sequence characters match only one character in the string.
\d Any digits [0-9]
\D Represents any non-digit
\s Represents white space \t\n\r\f\v
\S Represents non-white space character
\w Alphanumeric
\W Non alphanumeric
\b A space around words
\A Matches only at start of the string
\Z Matches only at end of the string
- \w represents 1 alphanumeric character
- [\w]* - * is zero or more repetition
- All strings starting with ‘a’ it can be written as
o r‘a[\w]*’

4|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

Question:- Write a program to create a RE to retrieve all words starting with ‘a’ in a
given string
import re
str='an apple a day keeps the Dr away'
result=re.findall(r'a[\w]*',str)
for s in result:
print(s)

output:-
an
apple
a
ay
away

What is wrong in above RE???


What modifications are required to get correct result???

import re
str='an apple a day keeps teh Dr away'
result=re.findall(r'\ba[\w]*\b',str)
for s in result:
print(s)

Output:-
an
apple
a
away

5|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

Create a RE to retrieve all words starting with a numeric digit


- r‘\d[\w]*’

Create a RE to retrieve all words having 5 character length…


- r ‘\d\w{5}\d’

Create a RE to retrieve all words having 3, 4 or 5 character length…


- r ‘\d\w{3,5}\d’

Quantifiers in RE
- Some characters are used to represent more than one character to be matched in
the string.
+ 1 or more repetitions
* 0 or more reparations
? 0 or 1
{m} Exactly m occurrences
{m,n} From m to n, m default 0 and n to infinity

A python program to create a regular expression to retrieve the phone number of a


person…
import re
str='Dr. Nageswara Rao: 999955560'
result=re.findall(r'\d+',str)
for s in result:
print(s,end='')

Question: - RE to Extract Name not Number??


import re
str='Dr. Nageswara Rao: 999955560'
result=re.findall(r'\D+',str)
for s in result:
print(s,end='')
RE to finds all words starting with either ‘an’ or ‘ak’…
r’a[nk][\w]*’
o It means either n or k or both after a…

6|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

SQLITE

Python has built-in support for SQLite in the form of the sqlite3 module. This module
contains functions for performing persistent CRUD operations on SQLite database.
The following command is used to install the sqlite3 package.

pip install pysqlite3

connect():

To establish a connection with a SQLite database, sqlite3 module needs to be imported and
the connect() function needs to be executed.

>>> import sqlite3

>>> db=sqlite3.connect('test.db')

The connect() function returns a connection object referring to the existing database or a
new database if it doesn't exist.

The following methods are defined in the connection class:

Method Description
cursor() Returns a Cursor object which uses this Connection.
commit() Explicitly commits any pending transactions to the database. The method should be a
no-op if the underlying db does not support transactions.
rollback( This optional method causes a transaction to be rolled back to the starting point. It
) may not be implemented everywhere.
close() Closes the connection to the database permanently. Attempts to use the connection
after calling this method will raise a DB-API Error.

A cursor is a Python object that enables you to work with the database. It acts as a handle
for a given SQL query; it allows the retrieval of one or more rows of the result. Hence, a
cursor object is obtained from the connection to execute SQL queries using the following
statement:

>>> cur=db.cursor()

The following methods of the cursor object are useful.

7|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

Method Description
execute() Executes the SQL query in a string parameter
executemany() Executes the SQL query using a set of parameters in the list of tuples
fetchone() Fetches the next row from the query result set.
fetchall() Fetches all remaining rows from the query result set.
callproc() Calls a stored procedure.
close() Closes the cursor object.

execute():

The execute() method of the cursor receives a string containing the SQL query. A string
having an incorrect SQL query raises an exception, which should be properly handled.
That's why the execute() method is placed within the try block and the effect of the SQL
query is persistently saved using the commit() method. If however, the SQL query fails,
the resulting exception is processed by the except block and the pending transaction is
undone using the rollback() method.

CREATE TABLE query:


import sqlite3
db=sqlite3.connect('test.db')
try:
cur =db.cursor()
cur.execute('''CREATE TABLE student (
StudentID INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT (20) NOT NULL,
age INTEGER,
marks REAL);''')
print ('table created successfully')
except:
print ('error in operation')
db.rollback()
db.close()

E:\SQLite>sqlite3 test.db
SQLite version 3.25.1 2018-09-18 20:20:44
Enter ".help" for usage hints.
sqlite> .tables
student

Insert a Record:

import sqlite3
db=sqlite3.connect('test.db')

8|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

qry="insert into student (name, age, marks) values('Rajeev', 20, 50);"


try:
cur=db.cursor()
cur.execute(qry)
db.commit()
print ("one record added successfully")
except:
print ("error in operation")
db.rollback()
db.close()

sqlite> select * from student;


1|Rajeev|20|50.0

Retrieve Records:

1. fetchone(): Fetches the next available record from the result set. It is a tuple consisting
of values of each column of the fetched record.
2. fetchall(): Fetches all remaining records in the form of a list of tuples. Each tuple
corresponds to one record and contains values of each column in the table.

import sqlite3
db=sqlite3.connect('test.db')
sql="SELECT * from student;"
cur=db.cursor()
cur.execute(sql)
while True:
record=cur.fetchone()
if record==None:
break
print (record)
db.close()

students=cur.fetchall()
for rec in students:
print (rec)

Update a Record:

import sqlite3
db=sqlite3.connect('test.db')
qry="update student set age=? where name=?;"
try:
cur=db.cursor()
cur.execute(qry, (19,'Deepak'))

9|Page
SVKM’s NMIMS University
Mukesh Patel School of Technology Management & Engineering/ School of Technology
Management & Engineering
Course: Python Programming
PROGRAMME: B.(Tech.)/MBA(Tech.)
First Year AY 2023-2024 Semester: II

db.commit()
print("record updated successfully")
except:
print("error in operation")
db.rollback()
db.close()

Delete a Record:

import sqlite3
db=sqlite3.connect('test.db')
qry="DELETE from student where name=?;"
try:
cur=db.cursor()
cur.execute(qry, ('Bill',))
db.commit()
print("record deleted successfully")
except:
print("error in operation")
db.rollback()
db.close()

PRACTICAL 11
Part B (to be completed by students)

Regular Expression and SQLite


1. All the students are required to perform the given tasks in Jupyter Notebook
2. Create a new notebook for each experiment. The filename should be
RollNo_Name_Exp10)
3. In the first cell, the student must write his/her Name, roll no and class in the form of
comments
4. Every program should be written in separate cells and in the given sequence
5. After completing the experiment, download the notebook in pdf format. The filename
should be RollNo_Name_Exp11.pdf).
Note: - To download as a PDF, go to File and choose Print Preview. This will open a
new tab. Now, press Ctrl + P and opt to save as PDF.
OR
Download notebook as HTML and open downloaded html(webpage), press CTRL+P
and opt to save as PDF.
6. Upload the pdf on the web portal

10 | P a g e

You might also like