-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathex1.py
76 lines (67 loc) · 1.94 KB
/
ex1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
keywords = {"auto","break","case","char","const","continue","default","do",
"double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while","printf","scanf","%d","include","stdio.h","main"}
operators = {"+","-","*","/","<",">","=","<=",">=","==","!=","++","--","%"}
delimiters = {'(',')','{','}','[',']','"',"'",';','#',',',''}
def detect_keywords(text):
arr = []
for word in text:
if word in keywords:
arr.append(word)
return list(set(arr))
def detect_operators(text):
arr = []
for word in text:
if word in operators:
arr.append(word)
return list(set(arr))
def detect_delimiters(text):
arr = []
for word in text:
if word in delimiters:
arr.append(word)
return list(set(arr))
def detect_num(text):
arr = []
for word in text:
try:
a = int(word)
arr.append(word)
except:
pass
return list(set(arr))
"""
this is original function for detecting identifier
def is_identifier(token):
if token[0] in numbers or token in keywords:
return False
else:
return identifier(token)
def identifier(token):
if len(token)<2 and (token[0] in alphabets or token[0] in numbers or token[0] == "_"):
return True
elif token[0] in alphabets or token[0] in numbers or token[0] == "_":
return identifier(token[1:])
else:
return False
"""
def detect_identifiers(text):
k = detect_keywords(text)
o = detect_operators(text)
d = detect_delimiters(text)
n = detect_num(text)
not_ident = k + o + d + n
arr = []
for word in text:
if word not in not_ident:
arr.append(word)
return arr
with open('e1-example.txt') as t:
text = t.read().split()
print("Keywords: ",detect_keywords(text))
print("Operators: ",detect_operators(text))
print("Delimiters: ",detect_delimiters(text))
print("Identifiers: ",detect_identifiers(text))
print("Numbers: ",detect_num(text))