
次の構造を含む HTML ファイルがあります。
<h1 class="section">First title</h1>
<div><h2 class="chapter">Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">Chapter title</h2>
Chapter text here.
<h1 class="section">Second title</h1>
<div><h2 class="chapter">Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">Chapter title</h2>
Chapter text here.
次のように、章のタイトルの前に番号を追加したいと思います。
<h1 class="section">First title</h1>
<div><h2 class="chapter">1. Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">2. Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">3. Chapter title</h2>
Chapter text here.
<h1 class="section">Second title</h1>
<div><h2 class="chapter">1. Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">2. Chapter title</h2>
Chapter text here.
<div><h2 class="chapter">3. Chapter title</h2>
Chapter text here.
ヘッダーにカウンター リセット、カウンター インクリメントを使用して CSS で章番号を挿入しようとしましたが、これは特定のコンテキストでのみ機能します。
class="section" を検索し、章のタイトルの前に順番に番号を挿入できるスクリプト (python、perl、???) はありますか?
実際のファイルのサンプルを以下に示します。
<body><div class='root'><h1 class="section">Génesis</h1><div><h2
class="chapter">Dios ordena el universo</h2><div>01 En el principio,
cuando Dios creó los cielos y la tierra, </div><div>02 todo era
confusión y no había nada en la tierra. Las tinieblas cubrían los
abismos mientras el espíritu de Dios aleteaba sobre la superficie de
las ag [many lines here] </div><div><h2 class="chapter">Descanso del
séptimo día</h2><div>01 Así estuvieron [many lines here] <div
class='root'><h1 class="section">Éxodo</h1><div><h2 class="chapter">Los
hebreos se multiplican en Egipto</h2><div>01 Estos son los nombres de
los hijos de Israel que llegaron con Jacob a Egipto, cada uno con su
familia:</div><div>02 Rubén, Simeón, Leví, Judá,</div><div>03 Isacar,
[many lines here] etc, etc
答え1
編集
あなたのファイルを見たところ、問題は行末が規則的ではないことです。実際、ファイル全体が 1 行の長い行になっているように見えますが、それで正しいでしょうか?
私のスクリプトは、ファイルを1行ずつ解析することに依存しています。ファイルの実際の形式では、行がランダムに分割されているように見えるため、解析が非常に困難になります。もちろん、少し狂ったように表現されているように、ここただし、正規表現を使用して HTML を解析しないでください。
とはいえ、以下のスクリプトは投稿したファイルに対して機能します。
#!/usr/bin/perl
my $file=<>; ## Load the file into memory
my $a=1; ## Set up a counter
## Split the file on each occurence of
## 'class="chapter"' and save into the array @b
my @b=split(/class=.chapter.>/,$file);
## Print the beginning of the file
## and remove it from the array.
print shift(@b);
## Now, go through the array, adding the counter ($a)
## to each chapter heading.
foreach (@b) {
## Print 'class="chapter"', the counter and
## the rest of the text until the next chapter heading
print "class=\"chapter\">$a. $_";
$a++; ## Increment the counter
$a=1 if /class="section"/; ## reset the counter
}
答え2
答え3
CSS を使用すると、番号を自動的に付けることもできます。
a { counter-reset: section; }
h2:before {
counter-increment: section;
content: counter(section) ". ";
display: inline;
}