2012-11-15 46 views
1

我有一個文件,其中包含有機分子的幾個能量。 我想做一個python腳本,它允許我打印選定的能量,可以說第一個或第二個或最後一個或第三個最後一個,等等等等。 我正在學習python,並且我理解我應該做一個搜索列表,插入第二個參數,表明我想打印哪種能量。由於我正在學習,我不知道如何做到這一點。以下是我製作的腳本,但第一個腳本只是打印第一個能量,第二個腳本只是打印最後一個腳本。任何幫助,高度讚賞。 (這裏是我使用作爲輸入https://dl.dropbox.com/u/63216126/ActCat.out文件的一個例子的鏈接)Python搜索,列表和選定的打印

我做我做

import sys 
    import re 


    filename = sys.argv[1] 
    newfile = str(filename) + ".3d" 

    openold = open(filename,"r") 
    opennew = open(newfile,"w") 

    start = 0 

    rline = openold.readlines() 

    for i in range (len(rline)): 
     if "SCF Done" in rline[i]: 
      start = i 

    for line in rline[start:start+1] : 
     words = line.split() 
     energy = words[4] 
     print >>opennew, "The energy of the molecule is %s kcal mol-1" % energy 
     break 


    openold.close() 
    opennew.close() 

回答

0

你想

import sys 
    import re 

    filename = sys.argv[1] 
    newfile = str(filename) + ".3d" 

    openold = open(filename,"r") 
    opennew = open(newfile,"w") 


    rline = openold.readlines() 

    for line in rline: 
     if re.search(r"SCF Done", line): 
      words = line.split() 

      energy = float(words[4]) 

      print >>opennew, "The energy of the molecule is %f kcal mol-1" % energy 
      break 

    openold.close() 
    opennew.close() 

二碼一碼有選擇地選擇打印哪些能量?這將把所有能量集中到一個列表中,然後你可以在列表中索引來打印你想要的。請注意,我從循環中刪除了break,因此它收集了所有這些數據。

import sys 
import re 

filename = sys.argv[1] 
newfile = str(filename) + ".3d" 

openold = open(filename,"r") 
opennew = open(newfile,"w") 


rline = openold.readlines() 
energies = [] 
line_number = 0 
for line in rline: 
    line_number += 1 
    if re.search(r"SCF Done", line): 
     words = line.split() 

     energy = float(words[4]) 
     energies.append(("The energy of the molecule is %f kcal mol-1" % energy, line_number)) 

print >>opennew, energies[0] # print first energy and line number 
print >>opennew, energies[4] # print 5th energy and line number 
print >>opennew, energies[-1] # print last energy and line number 
print energies[1][0] # print energy 
print energies[1][1] # print line number 

openold.close() 
opennew.close() 
+0

非常感謝喬希,這是非常有幫助的。 但是,我仍然有一個問題,有沒有什麼方法可以知道和打印行數(在文件的長度),其中我打印的特定能量是。 – Justme

+0

當然,給我一秒我會更新我的答案 –