实用小工具-python esmre库实现word查找

python esmre库实现word查找

前言:
在文本中匹配特定的字符串,一般可以用普通的字符串匹配算法,KMP算法;
python中提供了一个库,esmre, 通过预先将字符串存到esm对象中,利用这些字符串从候选的字符串中进行匹配,返回匹配位置,支持同一个词语的多次匹配。效率比正则表达式快。

import esm
import re

index = esm.Index()
index.enter("he")
index.enter("she")
index.enter("his")
index.enter("hers")
index.fix()
query1 = "this here is history"
query2 = "Those are his sheep!"

# 使用esmre
out1 = index.query(query1)
out2 = index.query(query2)
print('out1=', out1, '\nstr1=', query1[out1[0][0][0]:out1[0][0][1]])
print('out2=', out2, '\nstr2=', query1[out2[0][0][0]:out2[0][0][1]])


# 使用正则表达式
out3 = re.search(r"he|she|his|hers", query1)
print('out3=',out3)

out4 = re.search(r"xxx|yyy", query2)
print('out4=',out4)

'''
out1= [((1, 4), 'his'), ((5, 7), 'he'), ((13, 16), 'his')] 
str1= his
out2= [((10, 13), 'his'), ((14, 17), 'she'), ((15, 17), 'he')] 
str2= is 
out3= <re.Match object; span=(1, 4), match='his'>
out4= None
'''

参考:
1.敏感词匹配——python使用esmre实现ac自动机[多模匹配]
2,.esmre 1.0.1
3.python ac模块_python使用esmre代替ahocorasick实现ac自动机[多模匹配]

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值