【问题标题】:replace first of   sequence with space character用空格字符替换序列的第一个
【发布时间】:2018-06-17 14:10:28
【问题描述】:

我有一个来自早期文本处理步骤的 HTML 格式的文本字符串。它是这样的,您会看到 any <SPACE> 字符已被   序列替换:

...this is some text    and some further   text...

现在,我想用 <SPACE> 字符替换文本中的 一些   序列。规则是:

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

生成的字符串应如下所示:

...this is some text    and some further   text...

对于使用 Python 的编程方法有什么想法吗?

【问题讨论】:

  • 向我们展示你的代码

标签: python html text


【解决方案1】:

问题可以简化为替换每个 ,而不是紧跟在另一个 之后

要实施此策略,请使用 re.sub 并带有否定的后视效果,如下所示:

import re

s = '...this is some text    \
     and some further   text...'

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多