这将是一个很长的问题,我希望你们有耐心。
我正在编写一个程序来检查分子式的语法是否正确。
我有一个BNF语法:
<formel>::= <mol> \n
<mol> ::= <group> | <group><mol>
<group> ::= <atom> |<atom><num> | (<mol>) <num>
<atom> ::= <LETTER> | <LETTER><letter>
<LETTER>::= A | B | C | ... | Z
<letter>::= a | b | c | ... | z
<num> ::= 2 | 3 | 4 | ...
这是我的代码:
from linkedQFile import LinkedQ
import string
import sys
ATOMER = ["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar"]
class FormelError(Exception):
pass
class Gruppfel(Exception):
pass
q = LinkedQ()
formel= "(Cl)2)3"
for symbol in formel:
q.put(symbol)
def readNum():
"""Reads digits larger than 1. Raises exception if condition is not fulfilled."""
try:
if int(q.peek()) >= 2:
print(q.peek())
q.get()
return
else:
q.get()
print("Too small digit at the end of row: "+getRest())
sys.exit()
except (ValueError,TypeError):
raise FormelError("Not a number.")
def readletter():
"""Reads lowercase letters and returns them."""
if q.peek() in string.ascii_lowercase:
print(q.peek())
return q.get()
else:
raise FormelError("Expected lowercase letter.")
def readLetter():
"""Reads capital letters and returns them."""
if q.peek() in string.ascii_uppercase:
print(q.peek())
return q.get()
else:
raise FormelError("Expected capital letter.")
def readAtom():
"""Reads atoms on the form X and Xx. Raises Exception if the format for an atom is not fulfilled or if the atom does not exist."""
X = ""
try:
X += readLetter()
except FormelError:
print("Missing capital letter at end of row: "+getRest())
sys.exit()
return
try:
x = readletter()
atom = X+x
except (FormelError, TypeError):
atom = X
if atom in ATOMER:
return
else:
raise FormelError("Unknown atom.")
def readGroup():
if q.peek() in string.ascii_uppercase or q.peek() in string.ascii_lowercase:
try:
readAtom()
except:
print("Unknown atom at end of row: "+getRest())
sys.exit()
try:
while True:
readNum()
except FormelError:
pass
return
if q.peek() == "(":
print(q.peek())
q.get()
try:
readMol()
except FormelError:
pass
if q.peek() == ")":
print(q.peek())
q.get()
else:
print("Missing right parenthesis at end of row: "+ getRest())
sys.exit()
return
digitfound = False
try:
while True:
readNum()
digitfound = True
except:
if digitfound:
return
print("Missing digit at end of row: "+getRest())
sys.exit()
return
raise FormelError("Incorrect start of group")
def readMol():
try:
readGroup()
except FormelError:
print("Incorrect start of group at end of row: "+getRest())
raise FormelError
if q.peek() == None:
return
if not q.peek() == ")":
try:
readMol()
except FormelError:
pass
def readFormel():
try:
readMol()
except:
return
print("Correct formula")
def getRest():
rest = ""
while not q.isEmpty():
rest += q.get()
return rest
readFormel()
现在代码应该接受一些给定的公式,并为某些给定的错误公式提供错误代码。让我们看看这些给定的公式:
正确: 的Si(C3(COOH)2)4(H 2 O)7
不正确: H 2 O)的Fe
(CL)2)3
程序接受正确的公式,但不幸的是也是错误的公式。原因是if语句在
中if not q.peek() == ")":
try:
readMol()
except FormelError:
pass
使得括号不对称(右侧有一个或多个括号太多)滑过代码,而不是被检测为“组”的错误启动。我怎样才能解决这个问题,同时仍然接受Si(C3(COOH)2)4(H2O)7作为语法正确的接受?
感谢您的耐心等待:)
答案 0 :(得分:1)
您的readMol代码有错误的测试(您甚至告诉过我们)&#34;)&#34;。如果您正在编码recursive descent parser,那么您的语法并不表示需要进行此类测试。
事实上,你的语法对于mol有一个奇怪的规则:
<mol> ::= <group> | <group><mol>
这对递归下降解析器不起作用。您已重构此类规则以共享每个规则中的公共前缀。在这种情况下,很容易:
<mol> ::= <group> ( <mol> | empty ) ;
然后直接从语法规则中编写代码(参见上面的链接) [你有点这样做,除了&#34;)&#34;校验。] 它应该看起来像这样(我不是python专家):
def readMol():
try:
readGroup()
except FormelError:
print("Incorrect start of group at end of row: "+getRest())
raise FormelError
try:
readMol()
except FormelError:
pass
在编写递归下降解析器时,首先将语法按到最兼容的形式(就像我对你的mol规则所做的那样)是很有帮助的。然后对单个识别器进行编码是一项纯粹的机械任务,很难出错。