【问题标题】:How to keep count of method calls within function executed? Python如何在执行的函数中保持方法调用的计数? Python
【发布时间】:2018-01-14 01:55:07
【问题描述】:

我的问题是如何计算“函数内的方法调用”?

我的意思是在下面的示例中,替换活动在函数内发生了两次。但我能做的就是运行一个计数器来检查:函数执行了多少次。

def replace (newString,i=[0]):
    oldString = 'This is word. This is another sample word.'
    newString = oldString.replace('word', 'WORD')
    print(newString)
    i[0]+=1
    return i[0]

如何统计函数内方法调用的执行次数,并在python中抛出一个输出来跟踪它?

Output: 
This is WORD. This is another sample WORD.
1

Expected output:
This is WORD. This is another sample WORD.
2

【问题讨论】:

  • 这没有什么意义,因为oldString.replace() 方法只发生一次。那为什么会是 2?
  • 我同意,但是如何跟踪方法调用?原因方法调用替换了两次。
  • 您似乎只是在寻找替换的元素数量,即'word'oldString 中出现的次数
  • 您可以查看profiling tools python 优惠。
  • 它替换了两次,但只调用了一次。

标签: python string counter


【解决方案1】:

正则表达式方法

import re
def replace(newString):
    oldString = 'This is word. This is another sample word.'
    newString = (re.sub('word', 'WORD', oldString))
    print newString
    print len(re.findall("WORD", newString))

输出:

This is WORD. This is another sample WORD.
2

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多