你可以混合使用正则表达式、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'<[^<]*?>')`