我目前正在尝试编写一段代码,在文本中的图形周围添加 html 粗体标记。
这是我的输入文本:
我认为他是 100% 的人。我认为他是一个 100% 的人。我认为他是一个 100% 的人
这是我想要的:
我认为他是一个 100% 的人。我认为他是一个 100% 的人。我认为他是一个 100% 的人。
但这就是我得到的:
我认为他是一个 100% 100% 的人。我认为他是一个 100 % 100 % 的人。我认为他是一个 100% 100% 的人。
import re
taggedOutput=""
myInput = "I think he was a 100 percent guy \n I think he was a 100 % \guy \n I think he was a 100 per cent guy"
pattern ="(([0-9]+ ?)(%|percent|per cent))"
regex = re.compile(pattern)
# I use re.split to isolate the content I want to tag... I guess the problem is there...
chunks = re.split(regex,myInput)
#For every chunk
for chunk in chunks:
if chunk != None:
matchStat = re.match(regex,chunk)
if matchStat:
taggedOutput += '<B>'+chunk+'</B>'
else :
taggedOutput += chunk
#print
print('<P>'+taggedOutput+'</P>')
提前致谢;)
最佳答案
使用re.sub()
而是通过 \1
引用捕获的组:
pattern = r"(([0-9]+ ?)(%|percent|per cent))"
print(re.sub(pattern, r"<b>\1</b>", myInput))
关于python - 在 Python 中围绕匹配项添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36266875/