实现说明
底层就是函数 overlapping。
驱动整个流程的是 while start != -1 这一个循环。
使用要点
- 跑完文件,输出里会留下标记——
empty fields:。 - 把
overlapping当作 API:导入它,其余代码可以忽略。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 overlapping。
入口签名:def overlapping(text, needle)
核心语句
def overlapping(text, needle):
hits, start = 0, text.find(needle)
while start != -1:
hits += 1
start = text.find(needle, start + 1)
return hits
代码示例
blob = "aaaa"
# "aa" 命中 [0:2],扫描跳到索引 2,所以是 2 次而不是 3 次
print(blob.count("aa"))
# 空串在任何位置都匹配:len + 1
print(blob.count(""))
# 统计支持 start/end 窗口,避免切片再计数
csv_row = "a,b,c,,d"
print("empty fields:", csv_row.count(",,"))
# 真正的重叠计数需要手写步进
def overlapping(text, needle):
hits, start = 0, text.find(needle)
while start != -1:
hits += 1
start = text.find(needle, start + 1)
return hits
print(overlapping(blob, "aa")) # 3:[0:2] [1:3] [2:4]
print(blob.count("z")) # 0 次也不报错