7

有没有办法在 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>
4

4 回答 4

6

看看 django.utils.text 中的truncate_html_words函数。即使您不使用 Django,那里的代码也完全符合您的要求。

于 2008-12-11T18:03:44.803 回答
3

听说Beautiful Soup非常擅长解析html。它可能能够帮助您获得正确的 html。

于 2008-12-11T16:58:58.243 回答
0

我要提到的是用 Python 构建的基本HTMLParser,因为我不确定你想要达到的最终结果是什么,它可能会或可能不会让你到达那里,你将主要使用处理程序

于 2008-12-11T17:07:16.230 回答
0

你可以混合使用正则表达式、BeautifulSoup 或 Tidy(我更喜欢 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)

输出是你想要的

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'<[^<]*?>')`
于 2008-12-11T18:24:11.800 回答