You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求无需使用enumerate()的文件行号统计及单词索引定位替代方案

替代enumerate()实现文件行号追踪的方案

需求:在文件中查找指定单词的全局索引,同时打印每行的行号及字符数量,要求避免在for循环中使用enumerate()来枚举行。

原代码(使用enumerate())

def find_word(f, word):
    g_indx = 0
    for line_num, line in enumerate(f, start=1):
        indx = 0 
        while (indx != -1):
            indx = line.find(word, indx)
            if indx > -1:
                yield g_indx + indx
                indx += 1
        print(f'Line number {line_num}, characters amount = {len(line)}')
        g_indx += len(line)

try:
    with open("out.txt", encoding="utf-8") as file:
        a = find_word(file, "Hello")
        print(list(a))
except FileNotFoundError:
    print("File cannot be found")
except:
    print("File handling error")

替代实现(手动维护行号)

核心思路是手动初始化并递增行号变量,替代enumerate()的行号生成功能,代码逻辑和原版本完全一致:

def find_word(f, word):
    g_indx = 0
    line_num = 1  # 手动初始化行号,从1开始
    for line in f:
        indx = 0 
        while (indx != -1):
            indx = line.find(word, indx)
            if indx > -1:
                yield g_indx + indx
                indx += 1
        print(f'Line number {line_num}, characters amount = {len(line)}')
        g_indx += len(line)
        line_num += 1  # 处理完一行后行号自增

try:
    with open("out.txt", encoding="utf-8") as file:
        a = find_word(file, "Hello")
        print(list(a))
except FileNotFoundError:
    print("File cannot be found")
except:
    print("File handling error")

说明

  • 手动初始化line_num = 1,对应原代码enumerate(f, start=1)的起始行号
  • 每次循环处理完一行后,执行line_num += 1来更新行号
  • 其余逻辑(全局索引计算、单词查找、打印行信息)完全保留原代码的功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:36:21