一个字符一个 Token 会切出几个
有人偷懒,把所有运算符和数字都一个字符切一个词(标识符和字符串仍然正常取)。输出这样切那段源码会得到几个 Token。
let rate = 12; let msg = "hi there"; total = rate >= 3;
KEYWORDS = ("let", "if", "else", "while")
TWO = ("==", "!=", ">=", "<=")
ONE = "+-*/=<>;()"
SRC = 'let rate = 12;\nlet msg = "hi there";\ntotal = rate >= 3;'
def lex_char_by_char(src):
toks, i, n = [], 0, len(src)
while i < n:
c = src[i]
if c in " \t\n":
i += 1; continue
if c.isalpha() or c == "_":
j = i
while j < n and (src[j].isalnum() or src[j] == "_"): j += 1
toks.append(src[i:j]); i = j; continue
if c == '"':
j = src.find('"', i + 1)
toks.append(src[i:j + 1]); i = j + 1; continue
toks.append(c); i += 1
return toks
print(len(lex_char_by_char(SRC)))
全部评论