在Python中如何按照指定的词数分割HTML?

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>

你想忽略标签,以便它们不会被分割吗?换句话说,只获取并拆分不包含在标签中的文本。 - monkut
你是否想要分割文档中被标签(例如<p>和</p>之间)包含的文本? - gotgenes
4个回答

6

请看django.utils.text中的truncate_html_words函数。即使您不使用Django,那里的代码也能完全满足您的需求。


3

我听说Beautiful Soup在解析html方面非常出色,它很可能能够帮助你正确地获取html。


0

我本来想提一下 Python 内置的 HTMLParser,但由于我不确定你想要达到的最终结果是什么,它可能会或可能不会帮助你,你主要需要与处理程序一起工作。


0
你可以使用正则表达式、BeautifulSoup或Tidy(我更喜欢BeautifulSoup)的混合方式。思路很简单-首先去掉所有HTML标签。找到第n个单词(这里n=7),找到第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'<[^<]*?>')`

你为什么要编写自己的函数来删除HTML标签,而不使用Beautiful Soup的soup.get_text()方法呢? - tatlar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接