Python自定义函数统计文件字符串时计数变量每次重置如何解决
解决方案
你当前代码的问题是每次调用func()时都会在函数内部重新创建局部变量c并赋值为0,调用结束后局部变量就会被销毁,自然无法累计计数。
推荐实现(完全封装统计逻辑)
不需要在主程序做遍历和计数,直接把文件句柄传给自定义函数,所有匹配、统计逻辑都在函数内部完成,完全符合你的需求:
def count_target_in_file(fhand, target_str="Temp"): count = 0 for line in fhand: if target_str in line.strip(): count += 1 return count # 主程序仅需调用函数拿结果 with open("file_address", encoding="utf-8") as fhand: total_count = count_target_in_file(fhand) print(total_count)
用with语句管理文件句柄可以自动完成文件关闭操作,避免资源泄露。
逐行传入场景的实现方案
如果有特殊需求必须在主程序遍历文件、逐行传入函数,可以通过让函数保留内部状态实现,两种常用方式:
- 方式1:使用函数属性存储计数
def func(a): # 第一次调用时初始化计数属性 if not hasattr(func, 'total'): func.total = 0 a = a.strip() if "Temp" in a: func.total += 1 return func.total fhand = open("file_address") for i in fhand: current_total = func(i) print(current_total)
- 方式2:使用闭包保留状态
def create_counter(target_str="Temp"): count = 0 def counter(line): nonlocal count line = line.strip() if target_str in line: count += 1 return count return counter # 主程序逻辑 func = create_counter() with open("file_address") as fhand: for i in fhand: current_total = func(i) print(current_total)
内容的提问来源于stack exchange,提问作者Chetan Lohani
相关产品推荐
相关产品推荐

