如何将文本文件的每一行存入Python列表,排除注释

-3 投票
1 回答
1525 浏览
提问于 2025-04-18 11:15

我有一个教授问我,这个夏天有没有时间和兴趣去弄清楚他的一段Fortran 90程序为什么在有注释的版本里能正常工作,而在没有注释的版本里却不行。这个程序有几千行代码,所以我显然不可能手动去找错误。

我的想法是这样的:因为我不是专业程序员,但我决定把这个任务当作一个有趣的学习项目,同时也是帮教授一个忙。我打算写一个Python脚本,逐行读取文本文件,把每一行存入一个列表,排除掉注释行(以! COMMENT TEXT开头的行)和不包含任何代码的行(只有换行符的行)。

我把有注释和没有注释的Fortran源代码复制粘贴到两个文本文件里,分别叫c.txtunc.txt,并去掉了任何缩进。到目前为止,我的进展是这样的:

listCom = []
esclam = "!"
with open("c.txt") as f:
    i=0

    for line in f:
        line = line.strip()
        if line == "":
            continue
    if line.find(esclam) == -1:
        listCom.append(line)    

for e in listCom:
    print e 

这个代码是用来检查有注释版本的文本文件中的每一行是否正确存储到列表里的,但它并没有正常工作。我可能把问题搞得比实际情况更复杂了。任何建议都非常感谢。我的计划是对没有注释的文本文件重复同样的过程,然后逐条比较这两个列表,使用一个标志变量来告诉我在哪一条上它们不同,或者它们根本没有不同。

c.txt文件中,有注释版本的Fortran 90源代码示例如下:

! When this subroutine is run at double precision, 
! a good number is 7.


use constants
implicit none

complex(kind=double), intent(inout) :: A
complex(kind=double), intent(in) :: Q
integer, intent(in):: order,case_type,choice, comp_coeff
complex(kind=double), dimension(0:MAX_),intent(out) :: D_m
integer, intent(out):: k_max 
complex(kind=double),intent(out):: norm

pi=acos(-one)

G_2=cmplx(zero,zero,double)
G_1=cmplx(zero,zero,double )

!FL=2.0D0**126
FL=D1mach(2)

1 个回答

1
with open('file.txt', 'r') as f:
    f = f.read().splitlines()
lines = [x for x in f if x and not x.strip().startswith('!')]

lines 是一个列表,里面包含了所有的Fortran代码行,去掉了注释行和空白行。

for line in lines:
    print(line)

将会打印

use constants
implicit none
complex(kind=double), intent(inout) :: A
complex(kind=double), intent(in) :: Q
integer, intent(in):: order,case_type,choice, comp_coeff
complex(kind=double), dimension(0:MAX_),intent(out) :: D_m
integer, intent(out):: k_max
complex(kind=double),intent(out):: norm
pi=acos(-one)
G_2=cmplx(zero,zero,double)
G_1=cmplx(zero,zero,double )
FL=D1mach(2)

针对你的示例文件。

撰写回答