如何在python中打开一个文件,阅读注释(“#”),在注释后面找到一个单词,然后选择它后面的单词?

2024-10-02 18:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

"#" 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")

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


Tags: 文件方法函数功能内容linecontent单词
3条回答

您应该先将文件读入一个列表,然后再进行处理:

file = 'test.txt' #<- call file whatever you want
with open(file, "r") as f:
    txt = f.readlines()
    for line in txt:
        if line.startswith ('"#"'):
            word = line.split(" Column.4: ")
            try:
                print(word[1])
            except IndexError:
                print(word)
        else:
            print("n")

输出:

>>> ['"#" XDI/1.0 XDAC/1.4 Athena/0.9.25\n']
>>> pre_edge

使用了try-and-except-catch,因为第一行也以“#”开头,我们不能用当前的逻辑拆分它。你知道吗

另外,作为旁注,在这个问题中,您有一个以“#”开头并带有引号的文件,因此startswith()函数被更改为这样。你知道吗

with open('stuff.txt', 'r+') as f:
    data = f.readlines()

for line in data:
    words = line.split()
    if words and ('#' in words[0]) and ("Column.4:" in words):
        print(words[-1])

# pre_edge

如果#注释包含上面提到的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()(如其他答案中所述)也是一种很好的做法,因为这样您就不会将所有行加载到内存中,而是逐个执行它们。你知道吗

相关问题 更多 >