Фон вопроса:
Мне нужно 'textwrap' для строки HTML, чтобы элементы <br>
были применены только к * тексту внутри HTML string.
Я могу применить стили к текстовым строкам (если требуется только один тип стилизации).
Однако добавление стилей к этой строке еще больше смешивает фактический текст с тегами стиля (очевидно).
Пример:
s = 'Here is a string'
styled_str = styling_func1(s)
print(styled_str)
# >>> "<font color='black'>Here</font> is a string"
styled_str = syling_func2(styled_str)
print(styled_str)
# >>> "<font <br>color='black'>Here</font> is a string"
Как видите, <br>
застревает в тегах, если styling_func2
работает со строкой.
Мне нужна функция, которая добавляет <br>
элементов каждые ~ N символов или слов, не вызывая этих конфликтов.
Попытки решения:
from bs4 import BeautifulSoup
s = "Author Correction: Hybrid organic-inorganic polariton laser<span style="color:red">.. A correction to this article has been published and is linked from the HTML and PDF versions of this paper. The error has </span>not<span style="color:red"> been fixed in the paper.</span> ========= Publisher Correction: Predictors of chronic kidney disease in type 1 diabetes: a longitudinal study from the AMD Annals initiative<span style="color:red">.. A correction to this article has been published and is linked from the HTML and PDF versions of this paper. The error has </span><span style="color:red"> been fixed in the paper.</span>"
soup = BeautifulSoup(s)
# How to keep the previous tags while inserting these breaks?
"<br>".join(textwrap.wrap(soup.get_text(), 50))
Пример тестовых данных:
ввод строки:
<html><body><p>Author Correction: Hybrid organic-inorganic polariton laser<span style="color:red">.. A correction to this article has been published and is linked from the HTML and PDF versions of this paper. The error has </span>not<span style="color:red"> been fixed in the paper.</span> ========= Publisher Correction: Predictors of chronic kidney disease in type 1 diabetes: a longitudinal study from the AMD Annals initiative<span style="color:red">.. A correction to this article has been published and is linked from the HTML and PDF versions of this paper. The error has </span><span style="color:red"> been fixed in the paper.</span></p></body></html>
т.е.
Исправление автора : Hybrid Organi c -inorgani c Polariton Laser .. Исправление к этой статье было опубликовано и связано с HTML и PDF-версиями этой статьи. Ошибка не была исправлена в статье. ========= Исправление издателя: Предикторы хронической c болезни почек при диабете 1 типа: продольное исследование от AMD Инициатива Annals .. Исправление к этой статье было опубликовано и связано с HTML и PDF-версиями этого документа. Ошибка была исправлена в бумаге.
(где жирный шрифт будет красным)
Желаемый вывод:
<html><body><p>Author Correction: Hybrid organic-inorganic <br>polariton laser<span style="color:red">.. A correction to this article has <br>been published and is linked from the HTML and PDF <br>versions of this paper. The error has </span>not<span style="color:red"> been <br>fixed in the paper.</span> ========= Publisher <br>Correction: Predictors of chronic kidney disease <br>in type 1 diabetes: a longitudinal study from the <br>AMD Annals initiative<span style="color:red">.. A correction to this <br>article has been published and is linked from the <br>HTML and PDF versions of this paper. The error has </span><span style="color:red"> <br>been fixed in the paper.</span></p></body></html>
т.е.
Автор Исправление: Гибридный орган c -inorgani c поляритон
лазер .. Исправление к этой статье имеет
был опубликован и связан с версиями HTML и PDF
этого документа. Ошибка не была
исправлена в статье. ========= Издатель
Исправление: Предикторы хронического c заболевания почек
при диабете 1 типа: продольное исследование по инициативе
AMD Annals .. Поправка к этому
статья была опубликована и связана с версиями
HTML и PDF этой статьи. Ошибка
была исправлена в статье.