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

在 Python 中,enumerate 本身不直接用于统计文本,但它可以帮你遍历文本的每一行或每个字符,并结合其他逻辑实现统计功能。通常,enumerate 用来获取元素的同时获得其索引,这在处理文本时非常有用,比如标记行号或位置。
当你读取一个文本文件或文本列表时,可以用 enumerate 给每一行加上行号,同时进行内容分析或条件统计。
text_lines = [
"Hello world",
"Python is great",
"I love coding"
]
line_count = 0
for i, line in enumerate(text_lines, start=1):
print(f"Line {i}: {line}")
line_count += 1
print(f"Total lines: {line_count}")
结合 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")
如果要统计某个字符在字符串中的出现位置,也可以用 enumerate 遍历每个字符。
如果您是新用户,请直接将本程序的所有文件上传在任一文件夹下,Rewrite 目录下放置了伪静态规则和筛选器,可将规则添加进IIS,即可正常使用,不用进行任何设置;(可修改图片等)默认的管理员用户名、密码和验证码都是:yeesen系统默认关闭,请上传后登陆后台点击“核心管理”里操作如下:进入“配置管理”中的&ld
0
立即学习“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)}")
从文件中读取文本,使用 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中统计文本?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号