python - 如何在python中打开文件,阅读注释 ("#"), 找到注释后面的单词并选择它后面的单词?

标签 python if-statement string-matching

我有一个循环遍历文件的函数,如下所示:

"#" XDI/1.0 XDAC/1.4 Athena/0.9.25

"#" Column.4:                      pre_edge

Content

也就是“#”后面有注释。我的函数旨在读取每一行,如果它以特定单词开头,则选择“:”之后的内容

例如,如果我有这两行。我想通读它们,如果该行以“#”开头并包含单词“Column.4”,则应存储单词“pre_edge”。

我当前方法的示例如下:

with open(file, "r") as f:
        for line in f:
            if line.startswith ('#'):
                word = line.split(" Column.4:")[1]
            else:
                print("n")

我认为我的问题是在找到以“#”开头的行之后,我该如何解析/搜索它?如果它包含所需的词,则保存其内容。

最佳答案

如果 # 注释包含 str Column.4: 如上所述,您可以这样解析它。

with open(filepath) as f:
    for line in f:
        if line.startswith('#'):
            # Here you proceed comment lines
            if 'Column.4' in line:
                first, remainder = line.split('Column.4: ')
                # Remainder contains everything after '# Column.4: '
                # So if you want to get first word ->
                word = remainder.split()[0]
        else:
            # Here you can proceed lines that are not comments
            pass

注意事项

此外,使用 for line in f: 语句而不是 f.readlines()(如其他答案中所述)也是一个好习惯,因为这样你不要将所有行都加载到内存中,而是一条一条地执行。

关于python - 如何在python中打开文件,阅读注释 ("#"), 找到注释后面的单词并选择它后面的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54449176/

相关文章:

python - 实现 "[command] [action] [parameter]"风格的命令行界面?

c++ - 将两个二进制数组与阈值进行比较(近似匹配)

java - 在正则表达式 :java 中获取非法字符范围

python - 在 python 中一段时间​​后关闭 tkmessagebox

python - 一对多关系 NoForeignKeysError

python - 为什么我在 2017-03-12 的 12 点到凌晨 1 点之间的时间戳在 python 中得到 NonExistentTimeError

java - 在编程中 !(~A && ~B) 比 (A||B) 好吗?

delphi - 如果然后否则循环问题德尔福

ios - 在 Objective-C 中检查 bool 值数组并查看是否至少有一个为 YES

c - 使用 C 验证字符串中的子字符串