如何用enumerate在python中统计文本?

enumerate通过提供索引辅助文本统计,可遍历行或字符实现行号标记、关键词定位及出现次数统计,结合条件判断完成具体统计任务。

如何用enumerate在python中统计文本?

在 Python 中,enumerate 本身不直接用于统计文本,但它可以帮你遍历文本的每一行或每个字符,并结合其他逻辑实现统计功能。通常,enumerate 用来获取元素的同时获得其索引,这在处理文本时非常有用,比如标记行号或位置。

1. 使用 enumerate 遍历文本行并统计行号

当你读取一个文本文件或文本列表时,可以用 enumerate 给每一行加上行号,同时进行内容分析或条件统计。

text_lines = [    "Hello world",    "Python is great",    "I love coding"]line_count = 0for i, line in enumerate(text_lines, start=1):    print(f"Line {i}: {line}")    line_count += 1print(f"Total lines: {line_count}")

2. 统计包含特定词的行及其位置

结合 enumerate 和条件判断,可以找出哪些行包含某个词,并记录行号。

keyword = "Python"matches = []for i, line in enumerate(text_lines):    if keyword.lower() in line.lower():        matches.append(i)print(f"Keyword '{keyword}' found in lines: {matches}")print(f"Found in {len(matches)} lines")

3. 统计字符位置(逐字符遍历)

如果要统计某个字符在字符串中的出现位置,也可以用 enumerate 遍历每个字符。

立即学习“Python免费学习笔记(深入)”;

text = "hello"target = 'l'positions = []for i, char in enumerate(text):    if char == target:        positions.append(i)print(f"'{target}' appears at positions: {positions}")print(f"Total occurrences: {len(positions)}")

4. 实际应用:读取文件并统计关键词出现的行

从文件中读取文本,使用 enumerate 记录行号,便于后续分析。

filename = "sample.txt"keyword = "error"with open(filename, 'r', encoding='utf-8') as file:    error_lines = []    for line_num, line in enumerate(file, start=1):        if keyword in line:            error_lines.append(line_num)print(f"'{keyword}' found in lines: {error_lines}")print(f"Total: {len(error_lines)} occurrences")

基本上就这些。enumerate 的作用是提供索引,真正的“统计”靠的是你写的逻辑,比如计数、条件判断和存储结果。它让位置追踪变得简单直观。

以上就是如何用enumerate在python中统计文本?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1382875.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月15日 00:37:02
下一篇 2025年12月15日 00:37:15

相关推荐

发表回复

登录后才能评论
关注微信