首页 > 解决方案 > Python函数捕获变量

问题描述

我开始用 Python 编写代码。我遇到了这个问题。我正在通过为此创建一个函数在我的文件句柄变量中搜索一个字符串。但是,每次我遍历文件句柄变量中的行并将其传递给函数时,我在函数中用于计数的变量都会初始化为 0。有没有办法捕获字符串出现的次数一个文件,通过定义一个函数而不是在主程序中计数?

def func(a): 
    c=0
    a=a.strip()
    if "Temp" in a:
        c+=1
    return c

fhand=open("file_address")

for i in fhand:
    print(func(i))
    

标签: pythonfunction

解决方案


If you want the function to do all the counting, you can put the whole loop into the function. Then use the count method to get the number of "Temp"s in each line:

def func(fhand):
    c=0
    for a in fhand:
        c += a.count('Temp')
    return c

fhand=open("file_address")

print(func(fhand))

推荐阅读