用空格字符替换序列的第一个

时间:2018-06-17 14:10:29

标签: python html text

我有一个来自早期文本处理步骤的HTML格式的文本字符串。它是这样的,你看到任何 <SPACE>字符已被&nbsp;序列取代:

...this&nbsp;is&nbsp;some&nbsp;text&nbsp;&nbsp;&nbsp;&nbsp;and&nbsp;some&nbsp;further&nbsp;&nbsp;&nbsp;text...

现在,我想用&nbsp;字符替换文本中<SPACE>个序列的部分。规则是:

  • 使用单个&nbsp;字符替换任何单个 <SPACE>序列
  • 使用单个&nbsp;字符替换一系列&nbsp;序列中的第一个 <SPACE>序列

结果字符串应如下所示:

...this is some text &nbsp;&nbsp;&nbsp;and some further &nbsp;&nbsp;text...

有关使用Python的程序化方法的任何想法吗?

1 个答案:

答案 0 :(得分:1)

问题可以缩短为替换在&nbsp; 之后不会立即出现的每个&nbsp;

要实施此策略,请使用re.sub,并使用负面的后观,如下所示:

import re

s = '...this&nbsp;is&nbsp;some&nbsp;text&nbsp;&nbsp;&nbsp;&nbsp;\
     and&nbsp;some&nbsp;further&nbsp;&nbsp;&nbsp;text...'

print(re.sub(r'(?<!&nbsp;)&nbsp;', ' ', s))
# ...this is some text &nbsp;&nbsp;&nbsp;and some further &nbsp;&nbsp;text...