Найти и вставить теги с помощью регулярных выражений - PullRequest
0 голосов
/ 17 июня 2019

Я конвертирую книгу из PDF в epub калибра. Но заголовки не находятся внутри тегов заголовка, поэтому пытаемся заменить его на функцию python, используя регулярное выражение.

пример текста:

<p class="calibre1"><a id="p1"></a>Chapter 370: Slamming straight on</p>
<p class="softbreak"> </p>
<p class="calibre1">Hearing Yan Zhaoge’s suggestion, the Jade Sea City martial practitioners here were all stunned.</p>
<p class="calibre1"><a id="p7"></a>Chapter 372: Yan Zhaoge’s plan</p>
<p class="softbreak"> </p>
<p class="calibre1">Yan Zhaoge and Ah Hu sat on Pan-Pan’s back, black water swirling about Pan-Pan’s entire body, keeping away the seawater as he shot forward at lightning speed.</p>

Я пытался использовать регулярные выражения с

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):

    pattern = r"</a>(?i)chapter [0-9]+: [\w\s]+(.*)<br>"
    list = re.findall(pattern, match.group())

    for x in list:
        x = "</a>(?i)chapter [0-9]+: [\w\s]+(.?)<br>"
        x = s.split("</a>", 1)[0] + '</a><h2>' + s.split("a>",1)[1]
        x = s.split("<br>", 1)[0] + '</h2><br>' + s.split("<br>",1)[1]
    return match.group()

и


def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    pattern = r"</a>(?i)chapter [0-9]+: [\w\s]+(.*)<br>"
    s.replace(re.match(pattern, s), r'<h2>$0')

Но все еще не получил ожидаемый результат. что я хочу это ...

Input

</a>Chapter 370: Slamming straight on</p>

выход

</a><h2>Chapter 370: Slamming straight on</h2></p>

тег h2 должен быть добавлен во всех подобных случаях

Ответы [ 2 ]

1 голос
/ 18 июня 2019

regex не должен использоваться для разбора xml. Увидеть : Почему невозможно использовать регулярные выражения для разбора HTML / XML: формальное объяснение в терминах непрофессионала (Why shouldn't you.. будет лучше название)

Однако вместо этого вы можете использовать BeautifulSoup:

from bs4 import BeautifulSoup
data = """<p class="calibre1"><a id="p1"></a>Chapter 370: Slamming straight on</p>
<p class="softbreak"> </p>
<p class="calibre1">Hearing Yan Zhaoge’s suggestion, the Jade Sea City martial practitioners here were all stunned.</p>
<p class="calibre1"><a id="p7"></a>Chapter 372: Yan Zhaoge’s plan</p>
<p class="softbreak"> </p>
<p class="calibre1">Yan Zhaoge and Ah Hu sat on Pan-Pan’s back, black water swirling about Pan-Pan’s entire body, keeping away the seawater as he shot forward at lightning speed.</p>
i t"""

soup = BeautifulSoup(data, 'lxml')


for x in soup.find_all('p', {'class':'calibre1'}):

    link = x.find('a')
    title = x.text
    corrected_title = soup.new_tag('h2')
    corrected_title.append(title)

    if link:
        x.string=''
        corrected_title = soup.new_tag('h2')
        corrected_title.append(title)
        link.append(corrected_title)
        x.append(link)

print(soup.body)

выход

<body>
    <p class="calibre1">
        <a id="p1">
            <h2>Chapter 370: Slamming straight on</h2>
        </a>
    </p>
    <p class="softbreak"> </p>
    <p class="calibre1">Hearing Yan Zhaoge’s suggestion, the Jade Sea City martial practitioners here were all stunned.</p>
    <p class="calibre1">
        <a id="p7">
            <h2>Chapter 372: Yan Zhaoge’s plan</h2>
        </a>
    </p>
    <p class="softbreak"> </p>
    <p class="calibre1">Yan Zhaoge and Ah Hu sat on Pan-Pan’s back, black water swirling about Pan-Pan’s entire body, keeping away the seawater as he shot forward at lightning speed.</p>
    i t
</body>
0 голосов
/ 17 июня 2019

Комментарий Жана-Франсуа будет намного лучше следовать, но если бы нам, возможно, пришлось, я думаю, что мы начнем с этого выражения:

(<\/a>)([^<]+)?(<\/p>)
(<\/a>)(chapter\s+[0-9]+[^<]+)?(<\/p>)

заменяется на:

\1<h2>\2</h2>\3

Демо 1

Демо 2

Тест

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(<\/a>)(chapter\s+[0-9]+[^<]+)?(<\/p>)"

test_str = ("<p class=\"calibre1\"><a id=\"p1\"></a>Chapter 370: Slamming straight on</p>\n"
    "<p class=\"softbreak\"> </p>\n"
    "<p class=\"calibre1\">Hearing Yan Zhaoge’s suggestion, the Jade Sea City martial practitioners here were all stunned.</p>\n"
    "<p class=\"calibre1\"><a id=\"p7\"></a>Chapter 372: Yan Zhaoge’s plan</p>\n"
    "<p class=\"softbreak\"> </p>\n"
    "<p class=\"calibre1\">Yan Zhaoge and Ah Hu sat on Pan-Pan’s back, black water swirling about Pan-Pan’s entire body, keeping away the seawater as he shot forward at lightning speed.</p>")

subst = "\\1<h2>\\2</h2>\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.IGNORECASE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
...