code = """MODEL 0
..0...
..0...
..0...
ENDMDL
MODEL 1
..1...
..1..
..1...
ENDMDL
"""
with open("f.txt" , "w") as w:
w.write(code)
读取和分析演示数据:
import re
with open("f.txt", "r") as r:
allModels = r.read()
allM = {}
# the regex captures as few as possible things between
# MODEL and ENDMDL and captures the first number after
# MODEL as your modelnumber.
for m in re.findall(r"(MODEL\s+(\d+).+?ENDMDL)",allModels,re.DOTALL):
# create a dictionary entry for each found match-tuple
allM[int(m[1])] = m[0]
print(allM)
for k in allM:
with open("model_{}.txt".format(k),"w") as w:
w.write(allM[k])
此代码将按以下方式提取所有模型
你可以调整它只写一个数字
编写演示数据:
读取和分析演示数据:
输出(dict):
相关问题 更多 >
编程相关推荐