在python中的N个单词之后拆分HTML

rjm*_*nro 7 html python zope plone

有没有办法在N个单词之后拆分一长串HTML?显然我可以使用:

' '.join(foo.split(' ')[:n])
Run Code Online (Sandbox Code Playgroud)

获取纯文本字符串的前n个单词,但可能会在html标记的中间分割,并且不会生成有效的html,因为它不会关闭已打开的标记.

我需要在zope/plone站点中执行此操作 - 如果在那些可以执行此操作的产品中有标准的东西,那将是理想的.

例如,假设我有文字:

<p>This is some text with a 
  <a href="http://www.example.com/" title="Example link">
     bit of linked text in it
  </a>.
</p>
Run Code Online (Sandbox Code Playgroud)

我要求它在5个单词之后拆分,它应该返回:

<p>This is some text with</p>
Run Code Online (Sandbox Code Playgroud)

7个字:

<p>This is some text with a 
  <a href="http://www.example.com/" title="Example link">
     bit
  </a>
</p>
Run Code Online (Sandbox Code Playgroud)

Car*_*yer 6

看一下django.utils.text 中的truncate_html_words函数.即使你没有使用Django,那里的代码也完全符合你的要求.