0
我正在为使用Python的节点和连接编写一个文本文件解析器。
例如,文本文件看起来像这样:将节点连接到将来要创建的另一个节点
a
b
b <-> a # exists a connection between a/b
c
d
d <-> e # PROBLEM! this node connect to another node not yet being created
e
这是什么我试着用parsing.py
#blah blah
for line in raw:
if is_node(line):
add_node(NodeBuilder(line))
elif is_connection(line):
nameEndA, nameEndB = parse_connection(line)
endA = nodeDict[nameEndA]
# this line will receive KeyError because sometimes \
# the connection specifier is written before definition of the node
endB = nodeDict[nameEndB]
endA.connect(endB)
#definition of NodeBuilder and other functions
一个直观的方法来解决这个问题是延迟连接阶段,但是这表明解析必须分成两部分,其中Node对象必须处理原始文本。
#blah blah
for line in raw:
if is_node(line):
add_node(NodeBuilder(line))
elif is_connection(line):
nameEndA, nameEndB = parse_connection(line)
endA = nodeDict[nameEndA]
try:
endB = nodeDict[nameEndB]
endA.connect(endB)
except KeyError:
endA.txt2Parse(line)
for node in nodes:
if node.txt2Parse:
node.parse_and_connect() # has to parse raw data in Node object!!!
有没有更好的方法来设计这个没有不好的封装?
如果这是**工作代码**,你认为可以改进,参见[codereview.se。如果没有,请给出[mcve]清楚地表明问题。 – jonrsharpe