Python单词边界匹配

最近做一个NLP项目,涉及到字符串处理。

需求

把一些英语表达缩写替换成全称,例如pls替换please,BTW替换为by the way。

需要注意的点

只能替换独立的单词,不能把单词间的字母误替换为全称。例如某个单词含有pls,plsgiocephalic,这种情况下应该保留原单词,而非替换成pleasegiocephalic。此时就需要进行python的边界匹配

解决方法

边界匹配采用\b,写在哪边就是匹配哪边的边界,例如

  • 匹配左边边界
import re
# s是传入的需要处理的字符串
def replaceAcronyms(s):
	#将txs替换为thanks,re.I对大小写不敏感
	findAcro = re.compile(r"\btxs",re.I)
    s = re.sub(findAcro,"thanks",s)
    return s
test = "aaTXSbb,txsbb,TXS"
print(replaceAcronyms(test))

output:
aaTXSbb,thanksbb,thanks

  • 匹配右边边界
import re
# s是传入的需要处理的字符串
def replaceAcronyms(s):
	#将txs替换为thanks,re.I对大小写不敏感
	findAcro = re.compile(r"txs\b",re.I)
    s = re.sub(findAcro,"thanks",s)
    return s
test = "aaTXSbb,aatxs,TXS"
print(replaceAcronyms(test))

output:
aaTXSbb,aathanks,thanks

  • 匹配左右边界
# 需要引入re包
import re
# s是传入的需要处理的字符串
def replaceAcronyms(s):
	#将txs替换为thanks,re.I对大小写不敏感
	findAcro = re.compile(r"\btxs\b",re.I)
    s = re.sub(findAcro,"thanks",s)
    return s
test = "aaTXSbb,txs,TXS"
print(replaceAcronyms(test))

output:
aaTXSbb,thanks,thanks

*** 注意 ***
如果匹配左右边界失效,可以采用以下写法

str = "your str"
findAcro = re.compile(r"\b%s\b"%str,re.I)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值