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