python计算字符串匹配的准确率_计算python字符串中的匹配括号

这是一个基于堆栈的解决方案。当输入是某个控制字符时,仅计算整个字符串中的大括号会更快,但由于在键入之前进行文本选择和其他原因,这很棘手。这也不是非常pythonic,但它似乎工作,它相对较快:

#!/usr/bin/env python

import re

def bracecounter(s):

count = 0; open = 0; braces = []

for c in s:

if c in '()':

braces.append(c)

if c == '(':

open += 1

else:

if ''.join(braces[-2:]) == '()':

braces = braces[:-2]

if open == 1:

count += 1

open -= 1

else:

pass # closing brace without matching opening brace

return count

fix = [

(1, 'I have the string "(.*)"'),

(2, 'when user enters (\d+) times text "(.*)" truncate spaces'),

(0, 'I am in the middle of writing this ('),

(1, ') Nested ((braces) will (not) count))))))).'),

]

def test():

for exp, s in fix:

res = bracecounter(s)

assert exp == res, "Brace count %s != %s for '%s'" % (res, exp, s)

if __name__ == '__main__':

test()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值