forked from LiveCarta/BookConverter
Optimize "change_attrs_with_corresponding_tags" function
This commit is contained in:
@@ -158,48 +158,28 @@ class TagStyleConverter:
|
||||
|
||||
Returns
|
||||
-------
|
||||
to_remove: list
|
||||
styles_to_remove: list
|
||||
properties to remove
|
||||
|
||||
"""
|
||||
to_remove = []
|
||||
styles_to_remove = []
|
||||
for k in LiveCartaConfig.LIVECARTA_STYLE_ATTRS_SHOULD_BE_TAG:
|
||||
if f'{k[0]}:{k[1]}' in style:
|
||||
to_remove.append(k)
|
||||
return to_remove
|
||||
styles_to_remove.append(k)
|
||||
return styles_to_remove
|
||||
|
||||
def change_attrs_with_corresponding_tags(self, tag_initial_name: str):
|
||||
def change_attrs_with_corresponding_tags(self):
|
||||
# adds <strong>, <u>, <sup> instead of styles
|
||||
to_remove = self.check_style_to_be_tag(self.style)
|
||||
new_tags = []
|
||||
for i, (attr, value) in enumerate(to_remove):
|
||||
s = f'{attr}:{value};'
|
||||
self.style = self.style.replace(s, '')
|
||||
self.style = self.style.strip()
|
||||
if not i:
|
||||
self.tag_inline_style.name = LiveCartaConfig.LIVECARTA_STYLE_ATTRS_SHOULD_BE_TAG[(
|
||||
attr, value)]
|
||||
new_tags.append(self.tag_inline_style)
|
||||
else:
|
||||
name = LiveCartaConfig.LIVECARTA_STYLE_ATTRS_SHOULD_BE_TAG[(
|
||||
attr, value)]
|
||||
new_tag = BeautifulSoup(features='lxml').new_tag(name)
|
||||
new_tags[-1].wrap(new_tag)
|
||||
new_tags.append(new_tag)
|
||||
|
||||
top_tag = self.tag_inline_style
|
||||
|
||||
if new_tags:
|
||||
tmp_attrs = top_tag.attrs.copy()
|
||||
top_tag.attrs = {}
|
||||
top_tag2 = BeautifulSoup(features='lxml').new_tag(tag_initial_name)
|
||||
top_tag2.attrs = tmp_attrs
|
||||
if self.style:
|
||||
top_tag2.attrs['style'] = self.style
|
||||
new_tags[-1].wrap(top_tag2)
|
||||
else:
|
||||
top_tag.attrs['style'] = self.style
|
||||
return top_tag
|
||||
styles_to_remove = self.check_style_to_be_tag(self.style)
|
||||
for i, (attr, value) in enumerate(styles_to_remove):
|
||||
self.tag_inline_style.attrs['style'] = self.tag_inline_style.attrs['style']\
|
||||
.replace(f'{attr}:{value};', '').strip()
|
||||
corr_tag_name = LiveCartaConfig.LIVECARTA_STYLE_ATTRS_SHOULD_BE_TAG[(
|
||||
attr, value)]
|
||||
correspond_tag = BeautifulSoup(features='lxml').new_tag(corr_tag_name)
|
||||
for content in reversed(self.tag_inline_style.contents):
|
||||
correspond_tag.insert(0, content.extract())
|
||||
self.tag_inline_style.append(correspond_tag)
|
||||
|
||||
@staticmethod
|
||||
def wrap_span_in_tag_to_save_style_attrs(initial_tag):
|
||||
@@ -235,8 +215,7 @@ class TagStyleConverter:
|
||||
initial_tag.wrap(tag)
|
||||
|
||||
def convert_initial_tag(self):
|
||||
self.tag_inline_style = self.change_attrs_with_corresponding_tags(
|
||||
self.tag_inline_style.name)
|
||||
self.change_attrs_with_corresponding_tags()
|
||||
self.wrap_span_in_tag_to_save_style_attrs(self.tag_inline_style)
|
||||
return self.tag_inline_style
|
||||
|
||||
|
||||
Reference in New Issue
Block a user