Name: M.
Mukarram
Enrolment: 02-134192-054
Lab 6
Exercise 1
Extend your lexical analyser to ignore comments, defined as follows:
1. A comment begins with # and includes all characters until the end of that line.
2. A multiline comment begins with “””and includes all characters until ends at “”” or otherwise
end of that file.
Input:
import re
def stripComments(code):
code = str(code)
return re.sub(r'(?m)^ *//.*\n?', '', code)
print(stripComments("""#cyber security is my passion
my passion is cyber security
// buz"""))
Output:
Exercise 2
Write up a code to generate Token set of given Lexemes and store these tokens set in a text file.
Lexical analyzer that can handle following specification.
Input:
import re
kw = ["void", "main", "if", "print", "return", "for", "else", "switch", "case", "while"]
dt = ['int', 'float', 'double', 'char', 'bool']
aop = ['=']
pun = [',', ';']
brackets = ['(', ')', '{', '}']
mop = ['-', '+', '*', '/', '^']
id1 = ['++', '--']
rop = ['<=', '<', '>', '==', '>=']
lop = ['AND', 'OR', 'NOT']
identifier = []
flag = False
Name: M.Mukarram
Enrolment: 02-134192-054
dtflag = False
count = 0
str1 = "int num = 12 ; for ( int j = 0 ; j > i ; j ++ ){ print ( 'Hello' ) } ; "
num = re.findall('[0-9]+', str1)
string = re.findall('\'[a-zA-Z]+\'', str1)
check = str1.split(" ")
for c in check:
if (c == ' '):
continue
if (c == '\n'):
count = count + 1
continue
if (c in aop):
print(count, "assignment", c)
flag = True
continue
if (c in pun):
print(count, "Punctuator", c)
flag = True
continue
if (c in brackets):
print(count, "Brackets", c)
flag = True
continue
if (c in id1):
print(count, "increment decrement", c)
flag = True
continue
if (c in mop):
print(count, "mathematical operator", c)
flag = True
continue
if (c in rop):
print(count, "relational operator", c)
flag = True
continue
if (dtflag):
if (re.findall('^[a-zA-Z]+', c)):
dtflag = False
i = re.findall('^[a-zA-Z]+', c)
print(count, "Identifier", c)
identifier.append(i)
dtflag = False
else:
if (c in identifier):
print(count, "Identifier", c)
t = ''
dtflag = False
if c in num:
print(count, "number", c)
t = ''
Name: M.Mukarram
Enrolment: 02-134192-054
continue
if (c in string):
print(count, "string", c)
t = ''
continue
if (c in kw):
print(count, "keyword", c)
t = ''
continue
if (c in dt):
print(count, "datatype", c)
t = ''
Output:
Name: M.Mukarram
Enrolment: 02-134192-054