buf=[]
token=[]
def lex():
def read():
f=open('lex.txt','r')
data=f.readline()
data=data.split(' ')
return data
lex=read()
def operator(i):
op=['+','-','/','*','<','>','>=','<=']
if i in op:
buf.append(i)
token.append('RELOP')
return True
def error(i):
digit=[0,1,2,3,4,5,6,7,8,9,0]
try:
if i[0] in digit:
buf.append(i)
token.append('ERROR')
return True
except:
pass
def keyword(i):
keyword=['if','while','for']
if i in keyword:
buf.append(i)
x=i.upper()
token.append(x+'_TOKEN')
return True
def ident(i):
alph=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','q','r','s','t','u','v','w','x','y','z']
try:
if i[0] in alph:
buf.append(i)
token.append('ID')
return True
except:
pass
def floati(i):
try:
res = i.replace('.', '', 1).isdigit()
if res:
buf.append(i)
token.append('FLOAT')
return True
except:
pass
def integ(i):
try:
x=int(i)
buf.append(i)
token.append('INTEGER')
return True
except:
pass
count=0
for i in lex:
if keyword(i):
print(token[count])
continue
elif operator(i):
print(token[count])
continue
elif error(i):
print(token[count])
continue
elif floati(i):
print(token[count])
continue
elif integ(i):
print(token[count])
continue
elif ident(i):
print(token[count])
continue
else:
print("Zaaa anan xd")
count+1
lex()
I am trying to write a lexical analyzer in Python. I want to check an input string from a file for a float or integer, but when I use float()
my code changes the string type of integer to float and returns as float. I do not want to check string using float()
or int()
. I want to append the string to an array without changing it.