仅当以下行未注释时才提取注释行
Posted
技术标签:
【中文标题】仅当以下行未注释时才提取注释行【英文标题】: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()
【问题讨论】:
【参考方案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:
【讨论】:
刚刚修复了这个问题。但它不会修复代码以上是关于仅当以下行未注释时才提取注释行的主要内容,如果未能解决你的问题,请参考以下文章
Python图片颜色特征提取——HSV中心距法(附代码及注释)