Python中如何统计函数内部的方法调用次数?
统计Python函数内字符串替换的次数(或方法调用次数)
嘿,我明白你的需求了——你现在的代码统计的是自定义replace函数的调用次数,但你实际想要的是函数内部str.replace方法替换目标子串的次数(也就是原字符串里"word"被替换的数量,这里刚好是2次)。咱们分两种场景来解决:
场景1:统计str.replace替换的目标子串数量(符合你的期望输出)
str.replace方法本身一次调用就会替换所有非重叠的匹配项,所以它只执行了1次,但你要的是被替换的子串个数。可以用两种方式实现:
方法A:用str.count预统计子串数量
直接统计原字符串中目标子串的出现次数,再执行替换:
def replace(): oldString = 'This is word. This is another sample word.' # 先统计原字符串里"word"的数量 replace_count = oldString.count('word') # 执行替换 newString = oldString.replace('word', 'WORD') print(newString) return replace_count # 调用函数并打印结果 print(replace())
方法B:用re.subn直接获取替换结果和次数
如果需要处理更复杂的匹配(比如正则表达式),re.subn会更灵活,它会返回一个元组(替换后的字符串, 替换次数):
import re def replace(): oldString = 'This is word. This is another sample word.' # 执行替换并获取次数 newString, replace_count = re.subn(r'word', 'WORD', oldString) print(newString) return replace_count # 调用函数并打印结果 print(replace())
这两种方法运行后都会输出你想要的结果:
This is WORD. This is another sample WORD.
2
场景2:统计str.replace方法本身被调用的次数
如果你确实需要统计这个方法被调用的次数(比如函数内部多次调用str.replace),可以用装饰器来给方法添加计数器:
# 定义一个统计调用次数的装饰器 def count_method_calls(func): def wrapper(*args, **kwargs): wrapper.call_count += 1 return func(*args, **kwargs) # 初始化计数器 wrapper.call_count = 0 return wrapper # 给str.replace方法装上装饰器 str.replace = count_method_calls(str.replace) def replace(): oldString = 'This is word. This is another sample word.' # 第一次调用str.replace newString = oldString.replace('word', 'WORD') # 如果你再加一次调用,计数器就会变成2 # newString = newString.replace('sample', 'SAMPLE') print(newString) # 返回方法的调用次数 return str.replace.call_count # 调用函数并打印结果 print(replace())
这个方案里,每次调用str.replace,计数器都会加1。如果函数里只调用一次,返回1;多次调用则返回对应次数。
内容的提问来源于stack exchange,提问作者Programmer_nltk
相关产品推荐
相关产品推荐

