按有效行分组和累计计数
创始人
2024-08-22 23:00:44
0

以下是一个示例代码,用于按有效行分组和累计计数:

def count_valid_lines(filepath):
    # 打开文件
    with open(filepath, 'r') as file:
        lines = file.readlines()

    # 初始化计数器和结果字典
    count = 0
    result = {}

    # 遍历每一行
    for line in lines:
        line = line.strip()  # 去除行首尾的空白字符

        # 忽略空行和注释行
        if line == '' or line.startswith('#'):
            continue

        # 如果该行不在结果字典中,则将其添加到结果字典,并初始化计数为1
        if line not in result:
            result[line] = 1
        else:
            result[line] += 1

        # 增加有效行计数器
        count += 1

    # 打印结果
    print(f"有效行数:{count}")
    print("按行分组和计数:")
    for line, count in result.items():
        print(f"{line}: {count}")

# 示例用法
count_valid_lines("example.txt")

假设存在一个名为 "example.txt" 的文本文件,其中包含以下内容:

# 这是一个示例文件
apple
banana
# 注释行
apple
apple
banana
orange

运行上述代码后,输出结果将为:

有效行数:6
按行分组和计数:
apple: 3
banana: 2
orange: 1

相关内容

热门资讯

十分钟辅助!wepoker-h... 十分钟辅助!wepoker-h5下载,pokernow辅助控制,绝活教程(有挂实锤)1、点击下载安装...
5分钟辅助!aapoker辅助... 5分钟辅助!aapoker辅助器怎么用,wepoker模拟器哪个好用,模板教程(有挂辅助)wepok...
八分钟辅助!wpk官网下载链接... 八分钟辅助!wpk官网下载链接,wpk透视怎么安装,教程书教程(有挂分享)该软件可以轻松地帮助玩家将...
9分钟辅助!wepoker怎么... 9分钟辅助!wepoker怎么买辅助,wepoker安装教程,课程教程(有挂方略)1、wepoker...
第七分钟辅助!hh poker... 第七分钟辅助!hh poker插件下载,wepoker科技辅助器,教程书教程(有挂教程)wepoke...
三分钟辅助!hhpoker脚本... 三分钟辅助!hhpoker脚本下载,hhpoker辅助器,举措教程(有挂教程)三分钟辅助!hhpok...
第8分钟辅助!hhpoker的... 第8分钟辅助!hhpoker的辅助是真的吗,wepoker祈福有用吗,讲义教程(有挂解密)1、第8分...
6分钟辅助!hhpoker是真... 6分钟辅助!hhpoker是真的假的,hhpoker真的有透视吗,演示教程(真是有挂)1、每一步都需...
第七分钟辅助!we poker... 第七分钟辅助!we poker插件,we poker免费辅助器,手筋教程(有挂方式)暗藏猫腻,小编详...
七分钟辅助!aa poker辅... 七分钟辅助!aa poker辅助包,pokemmo脚本辅助器下载,讲义教程(有挂秘籍)1、pokem...