1

我有一个文件,其中包含来自有机分子的几种能量。我想制作一个允许我打印选定能量的python脚本,比如说第一个或第二个或最后一个或最后一个之前的第三个等等。我正在学习python,我知道我应该做搜索列表,插入第二个参数,指示我要打印的能量。由于我正在学习,我不知道如何做到这一点。这是我制作的脚本,但第一个脚本只打印第一个能量,第二个脚本只打印最后一个。非常感谢任何帮助。(这是一个链接,其中包含我用作输入的文件示例https://dl.dropbox.com/u/63216126/ActCat.out

我制作的第一个代码

    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()

我制作的第二个代码

    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()
4

1 回答 1

0

您想选择性地选择打印哪种能量吗?这会将所有能量收集到一个列表中,然后您可以索引该列表以打印您想要的。请注意,我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()
于 2012-11-15T03:02:36.547 回答