是否有任何方式后N个字分裂HTML的长字符串?很显然,我可以使用:

' '.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>
有帮助吗?

解决方案

看一看的 truncate_html_words 功能在django.utils.text。即使你不使用Django,代码有不正是你想要的。

其他提示

我听说美丽的汤是在解析HTML非常好。这将可能是能够帮助你获得正确的HTML了。

可以使用正则表达式,BeautifulSoup或整洁(我喜欢BeautifulSoup)的混合。 这个想法很简单 - 首先去除所有的HTML标签。查找第n个字(N = 7这里),找到的次数的第n个字出现的字符串,直到n个单词中 - 因为你正只想找最后出现的用于截断

下面是一段代码,虽然有点混乱,但工作原理

import re
from BeautifulSoup import BeautifulSoup
import tidy

def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)

input_string='<p>This is some text with a <a href="http://www.example.com/" '\
    'title="Example link">bit of linked text in it</a></p>'

s=remove_html_tags(input_string).split(' ')[:7]

###required to ensure that only the last occurrence of the nth word is                                                                                      
#  taken into account for truncating.                                                                                                                       
#  coz if the nth word could be 'a'/'and'/'is'....etc                                                                                                       
#  which may occur multiple times within n words                                                                                                            
temp=input_string
k=s.count(s[-1])
i=1
j=0
while i<=k:
    j+=temp.find(s[-1])
    temp=temp[j+len(s[-1]):]
    i+=1
####                                                                                                                                                        
output_string=input_string[:j+len(s[-1])]

print "\nBeautifulSoup\n", BeautifulSoup(output_string)
print "\nTidy\n", tidy.parseString(output_string)

的输出为u想要的

BeautifulSoup
<p>This is some text with a <a href="http://www.example.com/" title="Example link">bit</a></p>

Tidy
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<meta name="generator" content=
"HTML Tidy for Linux/x86 (vers 6 November 2007), see www.w3.org">
<title></title>
</head>
<body>
<p>This is some text with a <a href="http://www.example.com/"
title="Example link">bit</a></p>
</body>
</html>

希望这有助于

修改:一种更好的正则表达式

`p = re.compile(r'<[^<]*?>')`
scroll top