一条正则切出来和手写一样吗

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

把手写扫描器换成一条正则(规则顺序:关键字、标识符、数字、字符串、双字符运算符、单字符运算符),输出两个数:正则切出的词数,以及和手写结果内容不同的词有几个。

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;'

import re
PAT = re.compile(r'(?:let|if|else|while)\b|[A-Za-z_]\w*|\d+|"[^"]*"'
                 r'|==|!=|>=|<=|[+\-*/=<>;()]')
by_re = [m.group() for m in PAT.finditer(SRC)]
by_hand = ["let", "rate", "=", "12", ";", "let", "msg", "=", '"hi there"',
           ";", "total", "=", "rate", ">=", "3", ";"]
diff = sum(1 for a, b in zip(by_re, by_hand) if a != b)
print(str(len(by_re)) + "/" + str(diff))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论