【问题标题】:extract the commented lines only if the following line is not commented仅当以下行未注释时才提取注释行
【发布时间】:2021-07-28 08:50:27
【问题描述】:

我有一个文件如下:

cat file.txt

# unimportant comment
# unimportant comment
# unimportant comment
# important line
blah blah blah
blah blah blah
# insignificant comment
# significant comment
xyz
xyz

我想打印以'#' 开头的行,前提是以下行没有被注释。

我希望提取以下两行:

# important line
# significant comment

我尝试了以下方法,但它不起作用:

with open("file.txt","r") as fp:
    for line in fp:
        if line[0] == '#':
            pos = fp.tell()
            previous_line_comment = True
        elif line[0] != '#' and previous_line_comment:
            fp.seek(pos)
            print(fp.readline())
            previous_line_commented = False
        else:
            fp.readline()

【问题讨论】:

    标签: python seek


    【解决方案1】:

    让我们在迭代时存储每条评论的值,然后在遇到不是评论的行时输出上一行。

    with open('test.txt', 'r') as file:
        ## Set previous comment to None, we will store the comment in here
        previous_comment = None
        for line in file.readlines():
            ## We use startswith to return a boolean T/F if the string starts with '#'
            line_is_comment = line.startswith('#')
            
            if line_is_comment:
                ## If the current line is a comment, set the previous comment to the current line
                previous_comment = line
                continue
            elif previous_comment and not line_is_comment:
                ## If previous comment exists, and the current line is not a comment -> output
                print(previous_comment)
                previous_comment = None
            else:
                previous_comment = None
    

    输出

    # important line
    
    # significant comment
    

    【讨论】:

      【解决方案2】:

      & 是按位与运算符。我相信您打算使用的是逻辑 AND。

      elif line[0] != '#' and previous_line_comment:
      

      【讨论】:

      • 刚刚修复了这个问题。但它不会修复代码
      猜你喜欢
      • 2012-11-24
      • 2014-01-15
      • 2013-05-23
      • 1970-01-01
      • 2022-01-23
      • 2013-11-05
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多