0% found this document useful (0 votes)
13 views5 pages

4 B

NOTES

Uploaded by

shrinidhi N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

4 B

NOTES

Uploaded by

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

4.

bWrite a program to convert roman numbers in to integer values using dictionaries

def roman_to_int(roman):
roman_dict = {'I': 1, 'V': 5, 'X': 10,
'L': 50, 'C': 100, 'D': 500, 'M': 1000}
num = 0
for i in range(len(roman)):
if i > 0 and roman_dict[roman[i]] > roman_dict[roman[i-1]]:
num += roman_dict[roman[i]] - 2 * roman_dict[roman[i-1]]
else:
num += roman_dict[roman[i]]
return num

roman_numeral = 'MCMXCVI'
integer_value = roman_to_int(roman_numeral)
print(f"Roman Numeral: {roman_numeral}\nInteger Value:
{integer_value}")
5 a. Write a function called isphonenumber () to recognize a pattern 415-555-4242
without using regular expression and also write the code to recognize the same pattern
using regular expression

function called isphonenumber() that recognizes the pattern "415-555-4242" without


using regular expressions:

def isphonenumber(phone_number):
if len(phone_number) != 12: # Check if the length is
correct
return False

for i in range(0, 3):


if not phone_number[i].isdigit(): # Check if the
first 3 characters are digits
return False

if phone_number[3] != '-': # Check if the fourth


character is a hyphen

return False

for i in range(4, 7):


if not phone_number[i].isdigit(): # Check if the
next 3 characters are digits
return False

if phone_number[7] != '-': # Check if the eighth


character is a hyphen
return False

for i in range(8, 12):


if not phone_number[i].isdigit(): # Check if the
last 4 characters are digits
return False

return True
phone_number = "415-555-4242"
result = isphonenumber(phone_number)
print(result)
using regular expressions to recognize the same pattern:

import re

def isphonenumber(phone_number):
pattern = r"\d{3}-\d{3}-\d{4}" # Regular expression
pattern
return re.match(pattern, phone_number) is not None
phone_number = "415-555-4242"
result = isphonenumber(phone_number)
print(result)

import the re module, which stands for regular expressions.


Regular expressions (regex) are powerful patterns that can be used
to match and manipulate strings based on specific rules and patterns.
perform operations like searching, matching, replacing, and splitting
strings using regular expressions.
r prefix before the quotation mark indicates a raw string literal.
importing the re module, you gain access to various functions, such
as search(), match(), findall(), sub(), and more, which can be used to
work with regular expressions.
\d: This is a shorthand character class representing any digit from 0
to 9.
{3}: This specifies that the preceding pattern should occur exactly
3 times.
-: This matches the hyphen character "-".
So, the pattern r"\d{3}-\d{3}-\d{4}" is looking for three digits followed
by a hyphen, then another three digits followed by a hyphen, and finally
four digits.

Here's the syntax of the match() function:

re.match(pattern, string, flags=0)


 pattern: The regular expression pattern to match against.
 string: The input string to test the match against.
 flags (optional): Additional flags that modify the behavior of the
pattern matching.
code checks if the phone_number matches the specified pattern

using re.match(), and then it uses is not None to determine if a match was

found.
is not None is a comparison used to check if a variable or an object is not equal to

None If a match is found, it prints "True." Otherwise, it prints "False."

5 b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected])
import re

def search_contacts(file_path):
with open(file_path, 'r') as file:
 with: The with statement is used to manage resources automatically,
in this case, the file handling.
 open(file_path, 'r') : The open() function is used to open the file specified
by file_path in read mode ('r'). The 'r' argument indicates that the file
should be opened for reading.
 as file : The as keyword is used to create an alias (file in this case) for
the file object returned by the open() function. This alias can be used
to access the file object within the with block.

content = file.read()
The line of code content = file.read() reads the entire content of the opened file and
stores it in the variable content
phone_numbers = re.findall(r'\+\d{11}', content)
email_addresses = re.findall(r'\b[A-Za-z0-9._%+-]
+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', content)
findall(): The findall() function is a method of the re module that searches for all
occurrences of a specified pattern in the given string and returns them as a list.
\b: The \b is a word boundary anchor, which ensures that the pattern matches only
complete words (in this case, complete email addresses) and does not match within
other words.
print("Phone Numbers:")
for number in phone_numbers:
print(number)

print("\nEmail Addresses:")
for email in email_addresses:
print(email)

# Provide the file path to search in


file_path = 'C:/Users/DELL/Documents/sample.txt'
search_contacts(file_path)

open(file_path, 'r'): The open() function is used to open a file


specified by file_path.

 with: The with statement is used to manage resources automatically, in this


case, the file handling.
 open(file_path, 'r') : The open() function is used to open the file specified by
file_path in read mode ('r'). The 'r' argument indicates that the file should be
opened for reading.
 as file: The as keyword is used to create an alias ( file in this case) for the file
object returned by the open() function. This alias can be used to access the file
object within the with block.

By using the with statement, you ensure that the file is automatically closed once the
block of code indented under the with statement is executed, regardless of whether
the code block completes successfully or raises an exception.

You might also like