我有一个文件,其中包含此结构模型的信息,重复1到100:
MODEL <Number>
.....
.....
.....
ENDMDL
每个模型都有一个数字。模型信息以行MODEL <Number>
开始,以行ENDMDL
结尾。
我只想向一个新文件中写入一个型号。
答案 0 :(得分:0)
此代码将提取所有模型
您可以将其调整为只写一个数字。
编写演示数据:
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])
(字典的)输出:
{0: 'MODEL 0\n..0...\n..0...\n..0...\nENDMDL',
1: 'MODEL 1\n..1...\n..1..\n..1...\nENDMDL'}