例如有一个文本 blob
"Text blob1. Text blob2. Text blob3 45.6%. Text blob4."
我想用空格 ""
替换点,即 "."
。但同时,数字之间出现的点应该保留。例如,前面的示例应转换为:
"Text blob1 Text blob2 Text blob3 45.6% Text blob4"
如果我使用:
p = re.compile('\.')
s = p.sub(' ', s)
它将所有点替换为空格。
关于什么模式或方法在这里起作用有什么建议吗?
最佳答案
使用
\.(?!(?<=\d\.)\d)
参见proof 。此表达式将匹配前面有数字和点的任何后面没有数字的点。
说明
NODE EXPLANATION
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
) end of look-ahead
关于python - 替换字符串/句子中模式的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63093402/