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>
解決
を見てください。 truncate_html_words django.utils.text の関数。Django を使用していない場合でも、そこにあるコードはまさに必要なことを実行します。
他のヒント
それを聞いたことがあります 美しいスープ HTMLの解析が非常に得意です。おそらく、正しい HTML を取得するのに役立つでしょう。
ベースについて言及するつもりだった HTMLパーサー それは Python で構築されています。到達しようとしている最終結果が何であるかはわかりませんが、そこに到達するかどうかはわかりません。主にハンドラーを使用して作業します。
正規表現、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'<[^<]*?>')`