包装器,用于从正则表达式解析结果中获取更多功能。
tregex-tobiasli的Python项目详细描述
tregex
tregex
是python正则表达式的一个包装器,它使使用更平滑、更友好。
安装
pip install tregex-tobiasli
用法
importtregexastrt=tr.to_tuple(pattern='([^;]+?)@(.+?)\.([^;]+)',string='john.smith@somewhere.co.uk; hackzor@coolface.com')assertt[0][1]=='somewhere'assertt[1][2]=='com'pattern='(?P<name>[^;]+?)@(?P<address>.+?)\.(?P<domain>[^;]+)'t=tr.to_dict(pattern=pattern,string='john.smith@somewhere.co.uk; hackzor@coolface.com')assertt[0]['name']=='john.smith'assertt[1]['address']=='coolface't=tr.to_object(pattern=pattern,string='john.smith@somewhere.co.uk; hackzor@coolface.com')assertt[0].name=='john.smith'assertt[1].address=='coolface'
上面的方法模式可以是字符串或编译的正则表达式。TregexCompiled
是一个简单的
包含要在上述方法上运行的已编译正则表达式。如果模式很长,这种用法会加快速度
相当地。
fromtregeximportTregexCompiledpattern='(?P<name>[^;]+?)@(?P<address>.+?)\.(?P<domain>[^;]+)'trc=TregexCompiled(pattern)t=trc.to_object('john.smith@somewhere.co.uk; hackzor@coolface.com')assertt[0].name=='john.smith'
tregex还包含一些简单的模糊文本匹配方法,使用difflib.SequenceMatcher
:
fromtregeximportfind_bestplaces_in_wales=['Llanaber','Llanaelhaearn','Llanbedr','Llandbedrgoch','Llanbedrog','Llanberis','Llandanwg','Llanegryn','Llandegwning','Llandeiniolen','Llandwrog']best=find_best('Llanberris',places_in_wales)assertbest=='Llanberis'
其他方法是find
、find_scores
(返回与候选项一起匹配的分数)和similarity
(其中
返回一对字符串之间的分数。