我试图在查找单词的索引时打印行号和字符数。有人可以建议一种在 for 循环中不使用 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()
只需在循环中自己增加
line_num
变量即可。
def find_word(f, word):
g_indx = 0
line_num = 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