繁体   English   中英

阅读行时忽略注释(特定字符后的字符)

[英]Ignoring comments (characters after a certain character) when reading lines

你们中有人知道在 Py3 中逐行读取文件时去除注释的好方案吗? 如果可能的话,我根本不想使用正则表达式。

假设文件的内容类似于:

#first comment
while prime_count < n:#second comment
        for number in range(2, current):
            if current % number==0:#third comment
                break

我通常通过以下方式阅读内容:

file = open(refname, "r")
lines = file.readlines()
print(lines)

output 应该是:

    while prime_count < n:
            for number in range(2, current):
                if current % number==0:
                    break

任何指向某个方向的提示都会有所帮助。 大约 500 个文件将按 5000 个字符的顺序排列。

谢谢!

不要只open一个文件——它也需要关闭。 最好使用上下文管理with

with open(refname, "r") as file:
    # only keep those lines that do not start with a pound sign (after removing any whitespace)
    lines = [l for l in file.readlines() if not l.lstrip().startswith("#")]
print(lines)

感谢 bram-vanroy 指导我剥离/拆分 - 以前没有想到过。

with open(refname, "r") as file:
    for line in file:
        line = line.split('#', 1)[0]
        print(line)

会做我想做的。 在井号处拆分线,只保留第一部分。

另一个版本,去掉了多个空行,但使用正则表达式:

with open(refname) as file:
    for line in file:
        line = line.split('#', 1)[0]+"\n"
        line = re.sub(r'\n+', '\n',line)
        if line.strip():
            list.append(line)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM