python - 在python中用正则表达式将括号括起来
问题描述
我想在可以在句子中包含字母或点的表达式周围添加括号。
我试过这个功能:
def add_brackets(sentence, word):
s = r'(\b' + word + r'\b)'
c = re.compile(s, re.I)
return(c.sub(r'[\1]', sentence))
和
sentence = 'Le pressostat h.p. est installé'
word = 'est installé'
输出很好:
'Le pressostat h.p. [est installé]'
但是:
sentence = 'Le pressostat h.p. est installé'
word = 'pressostat h.p.'
输出没有括号:
'Le pressostat h.p. est installé'
但随着
sentence = 'Le pressostat h.p. est installé'
word = 'pressostat h.p' #no final dot
输出带有括号:
'Le [pressostat h.p]. est installé'
问题可能是最后的'。因为没有它,功能就可以工作。如何在正则表达式中包含点?
解决方案
推荐阅读
- javascript - 如何在画布上的不寻常形状上绘制网格
- bash - 命令执行后关闭 gnome_terminal 实例 (rpi)
- ansible - 如何获取 ansible playbook 运行更改的任务总数?
- c++ - Opencv中高斯的GIMP差异
- jquery - 如何在所有匹配的 jQuery 对象上使用 html2canvas
- django - 在模板中将多个字典变量作为一个发送
- excel - href 中的 Excel vba 声明
- dreamfactory - 电子邮件地址附加了 Facebook OAuth 服务的 DF 服务名称
- ajax - React Native 中的 axios 请求
- c# - 如何在datagridview中显示两个人之间的关系