You need to enable JavaScript to run this app. 如何用Python统计<ENDBLOCK>标签间总行数及#开头注释行数
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python统计<ENDBLOCK>标签间总行数及#开头注释行数

实现思路

通过逐行遍历文件内容,用临时变量记录当前<ENDBLOCK>块内的总行数和注释行数,每次遇到<ENDBLOCK>分隔标签就归档当前块的统计结果并重置临时变量,最后遍历所有块的统计结果完成校验即可。

完整实现代码

# 存储所有块的统计结果
total_line_list = []
comment_line_list = []
# 临时变量:统计当前块的行数、注释行数
current_total = 0
current_comment = 0

with open('10230_13.html', 'r', encoding='utf-8') as f:
    for line in f:
        # 匹配分隔标签行
        if line.strip() == '<ENDBLOCK>':
            # 归档当前块统计结果
            total_line_list.append(current_total)
            comment_line_list.append(current_comment)
            # 重置临时变量准备统计下一个块
            current_total = 0
            current_comment = 0
            continue
        # 非分隔行计入当前块总行数
        current_total += 1
        # 判断是否为注释行:line.lstrip().startswith('#')允许行首有空白,改为line.startswith('#')则严格要求行首第一个字符为#
        if line.lstrip().startswith('#'):
            current_comment += 1

# 输出统计结果(可按需删除)
for i in range(len(total_line_list)):
    print(f"块{i+1}:总行数{total_line_list[i]},注释行数{comment_line_list[i]}")

# 校验逻辑:块内总行数等于注释行数时输出提示
for i in range(len(total_line_list)):
    if total_line_list[i] == comment_line_list[i]:
        print(f"校验提示:第{i+1}个块内所有行均为注释行")

效果说明

对你给出的示例文件运行代码后,得到的统计结果和你预期的完全一致:

  • total_line_list = [3, 2, 3, 1]
  • comment_line_list = [1, 2, 1, 0]
    其中第2个块满足总行数等于注释行数的条件,会触发对应的提示输出。

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 22:06:03