在Python中N个单词后分割HTML
有没有办法将一长串HTML后的N个单词分割开? 显然我可以使用:
' '.join(foo.split(' ')[:n])
获取纯文本字符串的前 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>
我要求它在 5 个单词后分割,它应该返回:
<p>This is some text with</p>
7 个单词:
<p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit
</a>
</p>
Is there any way to split a long string of HTML after N words? Obviously I could use:
' '.join(foo.split(' ')[:n])
to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.
I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.
For example, say I have the text:
<p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit of linked text in it
</a>.
</p>
And I ask it to split after 5 words, it should return:
<p>This is some text with</p>
7 words:
<p>This is some text with a
<a href="http://www.example.com/" title="Example link">
bit
</a>
</p>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看一下 django.utils 中的 truncate_html_words 函数。文本。 即使您不使用 Django,那里的代码也完全可以满足您的需求。
Take a look at the truncate_html_words function in django.utils.text. Even if you aren't using Django, the code there does exactly what you want.
我听说 Beautiful Soup 非常擅长解析 html。 它可能能够帮助您获得正确的 html。
I've heard that Beautiful Soup is very good at parsing html. It will probably be able to help you get correct html out.
我要提到的是用 Python 构建的基本 HTMLParser ,因为我不确定你想要达到的最终结果是什么,它可能会也可能不会让你到达那里,你将主要与处理程序一起工作
I was going to mention the base HTMLParser that's built in Python, since I'm not sure what the end-result your trying to get to is, it may or may not get you there, you'll work with the handlers primarily
您可以混合使用正则表达式、BeautifulSoup 或 Tidy(我更喜欢 BeautifulSoup)。
这个想法很简单——首先去除所有 HTML 标签。 找到第 n 个单词(这里 n=7),找到第 n 个单词在字符串中出现的次数,直到 n 个单词 - 因为你只查找最后一个出现的单词以用于截断。
这是一段代码,虽然有点混乱但有效
输出就是你想要的
希望这有助于
编辑:更好的正则表达式
You can use a mix of regex, BeautifulSoup or Tidy (I prefer BeautifulSoup).
The idea is simple - strip all the HTML tags first. Find the nth word (n=7 here), find the number of times the nth word appears in the string till n words - coz u are looking only for the last occurrence to be used for truncation.
Here is a piece of code, though a bit messy but works
The output is what u want
Hope this helps
Edit: A better regex