python - 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))
解决方案
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))
推荐阅读
- php - XAMPP 7.2.5,未加载 mcrypt,opencart 2.3 需要
- java - 让 JasperReports 的 NullPointerException 进入多线程应用程序
- android - 如何从给定的颜色代码中了解位图 getPixel(x,y)
- c# - 如何确保 Mongodb 中只存在一个具有 X 值的文档
- javascript - 无需接触核心控制器即可调用扩展控制器并访问核心控制器功能
- ruby-on-rails - 如何获取实例的启动时间?
- java - 错误:异常构建过程终止,同时在 IntelIj 中编译 kotlin 文件
- f# - 如何访问 configureServices 中的配置
- sql - 创建表时 Mariadb SQL 语法错误
- swift - 使用 2 个 UIButtons 和一个 UILabel 重新创建 UIStepper,按钮不会按预期更新