Количество заголовков HTML

Количество заголовков HTML

У меня есть 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, используя counter-reset, counter-increment для заголовков, но это работает только в определенных контекстах.

Есть ли скрипт (python, perl, ???), который мог бы искать class="section", а затем последовательно вставлять числа перед названиями глав?

Вот пример самого файла:

<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

Редактировать

Теперь, когда я увидел ваш файл, проблема в том, что у вас нет регулярных окончаний строк. Фактически, похоже, что весь ваш файл — это одна длинная строка, так ли это?

Мой скрипт зависит от разбора вашего файла построчно. В реальном формате вашего файла строки, похоже, разбиты случайным образом, поэтому его будет очень трудно разобрать. Конечно, как было выражено довольно красноречиво, хотя и немного безумноздесь, никогда не следует анализировать 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

Вы, вероятно, можете использовать<ol>с<li>?

Я не уверен, что вы хотите сделать с этими <a>тегами, но ваши главы могут выглядеть примерно так:

<ol>
  <li class="chapter">Chapter title</li>
  <li class="chapter">Chapter title</li>
  <li class="chapter">Chapter title</li>
</ol>

И каждый новый набор <ol>элементов будет сбрасывать для вас нумерацию.

решение3

CSS также может помочь ему нумеровать автоматически:

a { counter-reset: section; }
h2:before {
    counter-increment: section;
    content: counter(section) ". ";
    display: inline;
}

Связанный контент