6

<h2>および<h3>タグに基づいて、HTML のブロック (完全なファイルではなく、コンテンツのみ) から目次を生成しようとしています。

これまでの私の計画は次のとおりでした。

  • を使用してヘッダーのリストを抽出しますbeautifulsoup

  • コンテンツに正規表現を使用して、ヘッダータグの前/内部にアンカーリンクを配置します(ユーザーが目次をクリックできるように)-内部を置き換える方法があるかもしれませんbeautifulsoup?

  • 事前定義された場所のヘッダーへのリンクのネストされたリストを出力します。

そう言うと簡単そうですが、後ろがちょっと面倒くさいです。

これらすべてを一度に実行して、車輪の再発明に次の数時間を無駄にしないようにするものはありますか?

例:

<p>This is an introduction</p>

<h2>This is a sub-header</h2>
<p>...</p>

<h3>This is a sub-sub-header</h3>
<p>...</p>

<h2>This is a sub-header</h2>
<p>...</p>
4

4 に答える 4

3

すぐにハッキングされた醜いコードの一部:

soup = BeautifulSoup(html)

toc = []
header_id = 1
current_list = toc
previous_tag = None

for header in soup.findAll(['h2', 'h3']):
    header['id'] = header_id

    if previous_tag == 'h2' and header.name == 'h3':
        current_list = []
    elif previous_tag == 'h3' and header.name == 'h2':
        toc.append(current_list)
        current_list = toc

    current_list.append((header_id, header.string))

    header_id += 1
    previous_tag = header.name

if current_list != toc:
    toc.append(current_list)


def list_to_html(lst):
    result = ["<ul>"]
    for item in lst:
        if isinstance(item, list):
            result.append(list_to_html(item))
        else:
            result.append('<li><a href="#%s">%s</a></li>' % item)
    result.append("</ul>")
    return "\n".join(result)

# Table of contents
print list_to_html(toc)

# Modified HTML
print soup
于 2010-03-25T12:43:38.387 に答える
1

を使用しlxml.htmlます。

于 2010-03-25T11:24:09.353 に答える
0

Łukasz が提案したソリューションの拡張バージョンを用意しました。

def list_to_html(lst):
    result = ["<ul>"]
    for item in lst:
        if isinstance(item, list):
            result.append(list_to_html(item))
        else:
            result.append('<li><a href="#{}">{}</a></li>'.format(item[0], item[1]))
    result.append("</ul>")
    return "\n".join(result)

soup = BeautifulSoup(article, 'html5lib')

toc = []
h2_prev = 0
h3_prev = 0
h4_prev = 0
h5_prev = 0

for header in soup.findAll(['h2', 'h3', 'h4', 'h5', 'h6']):
    data = [(slugify(header.string), header.string)]

    if header.name == "h2":
        toc.append(data)
        h3_prev = 0
        h4_prev = 0
        h5_prev = 0
        h2_prev = len(toc) - 1
    elif header.name == "h3":
        toc[int(h2_prev)].append(data)
        h3_prev = len(toc[int(h2_prev)]) - 1
    elif header.name == "h4":
        toc[int(h2_prev)][int(h3_prev)].append(data)
        h4_prev = len(toc[int(h2_prev)][int(h3_prev)]) - 1
    elif header.name == "h5":
        toc[int(h2_prev)][int(h3_prev)][int(h4_prev)].append(data)
        h5_prev = len(toc[int(h2_prev)][int(h3_prev)][int(h4_prev)]) - 1
    elif header.name == "h6":
        toc[int(h2_prev)][int(h3_prev)][int(h4_prev)][int(h5_prev)].append(data)

toc_html = list_to_html(toc)
于 2018-07-30T15:14:25.567 に答える
0

Python で HTML テキストの目次を生成するにはどうすればよいですか?

しかし、あなたは正しい軌道に乗っていると思います。車輪の再発明は楽しいものになるでしょう。

于 2010-03-25T12:08:52.007 に答える