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

在 Python 中,enumerate 本身不直接用于统计文本,但它可以帮你遍历文本的每一行或每个字符,并结合其他逻辑实现统计功能。通常,enumerate 用来获取元素的同时获得其索引,这在处理文本时非常有用,比如标记行号或位置。
1. 使用 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}")
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 的作用是提供索引,真正的“统计”靠的是你写的逻辑,比如计数、条件判断和存储结果。它让位置追踪变得简单直观。











