我有一個包含這些資訊的檔案
number of atoms
2
Atom labels, atom number, coords (Angstrom)
H 1 0.00000000 0.00000000 0.00000000
H 1 0.00000000 0.00000000 0.74080000
Overall charge
0
Number of basis funcs
2
Maximum number of primitives
我想提取以“Atom”開頭的行和以“Overall”開頭的行之間的行我嘗試使用下面的代碼,但沒有得到
H 1 0.00000000 0.00000000 0.00000000
H 1 0.00000000 0.00000000 0.74080000
我得到了一個沒有任何行的空檔案。
infile = open('h2_sample.input','r')
ouput = open('coordinate.txt','w')
copy = False
coordinate = []
for line in infile:
if line.strip() == "(Angstrom)":
copy = True
coordinate = []
elif line.strip() == 'Overall':
copy = False
for strings in coordinate:
output.write(strings '\n')
elif copy:
coordinate.append(line.strip())
你怎么看,我做錯了嗎?
uj5u.com熱心網友回復:
- 讀取檔案的所有行
- 找到要保留的行
- 寫入輸出檔案
with open("h2_sample.input.txt") as infile:
lines = infile.read().splitlines()
start = [i for i, line in enumerate(lines) if line.startswith("Atom ")][0]
end = [i for i, line in enumerate(lines) if line.startswith("Overall")][0]
with open("coordinate.txt", "w") as outfile:
outfile.write("\n".join(lines[start 1:end]))
輸出:
坐標.txt:
H 1 0.00000000 0.00000000 0.00000000
H 1 0.00000000 0.00000000 0.74080000
uj5u.com熱心網友回復:
編輯:作為答復所指出的那樣,你可能試圖檢查您的字串中的行。這也是一種有效的方法,我已經編輯了代碼塊來做到這一點。(我的原始答案也在下面。)
在 Python 中,string.strip()將洗掉前導和尾隨空格,不回傳第一個或最后一個單詞(當您使用它時)。你還需要使用output.close()和呼叫.readlines()上infile把它變成線的陣列。
infile = open('h2_sample.input', 'r').readlines()
ouput = open('coordinate.txt', 'w')
copy = False
coordinate = []
for line in infile:
if '(Angstrom)' in line:
copy = True
coordinate = []
elif 'Overall' in line:
copy = False
for strings in coordinate:
output.write(strings '\n')
elif copy:
coordinate.append(line)
output.close()
uj5u.com熱心網友回復:
第一的。您應該使用背景關系管理器,因為您沒有關閉檔案“infile”和“ouput”??或在最后使用 infile.close() 和 ouput.close() 嘗試:
with open('h2_sample.input','r') as infile, open('coordinate.txt','w') as ouput:
然后縮進寫行。Lineif line.strip() == "(Angstrom)":檢查 line 是否相等(Angstrom)。你應該使用:
if "(Angstrom)" in line.strip():
如果“Angstrom”符合要求,它將回傳 True。第一個 elif 陳述句也是如此。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343741.html
上一篇:如何將串列中的專案添加到PythonPandas中的資料框列?
下一篇:如何限制文本檔案中字串的數量
