So my problem is quite simple, my conditions are:
- if
"__"
in key, insert'class=\"\" '
into opening tag in value pair:<tag></tag>
so it becomes:<tag class=""></tag>
then insert the relevant values of"__"
- else leave
<tag></tag>
as is
I've done 95% of this but I'm missing one step. Here is my dict and code:
d1 = {
"h1": "<h1 class=\"my-heading\">[]</h1>",
"h1__display-3": "<h1 class=\" \">[]</h1>",
"h1__display-3_text-white_text-center": "<h1 class=\" \">[]</h1>",
"h1__mt-4": "<h1 class=\"\">[]</h1>",
"h1__mt-5": "<h1 class=\" \">[]</h1>",
"h1__mt-5_kakabum": "<h1 class=\" \">[]</h1>",
"h1__my-4": "<h1 class=\" \">[]</h1>",
"h2": "<h2>[]</h2>",
"h2__card-title": "<h2 class=\"\">[]</h2>",
"h2__mt-4": "<h2 class=\"\">[]</h2>",
"h2__my-4": "<h2 class=\"\">[]</h2>"
}
d2 = {k:k for k, v in d1.items()}
res = {}
for k in d2:
key = k.split('__')[0]
if key in d1:
res[k] = d1[key]
res2 = {k: re.sub(r'class="([\w\- ]+)"', r'class="\1 ' + d2[k] + '"', v) for k,v in res.items()}
res3 = {k: re.sub(r'\w\w\__', r'', v).replace('_', ' ') for k, v in res2.items()}
print('Res', json.dumps(res3, indent= 2))
After above I get undesired:
{
"h1": "<h1 class=\"my-heading h1\">[]</h1>", # notice the unnecessary 'h1' in class
"h1__display-3": "<h1 class=\"my-heading display-3\">[]</h1>",
"h1__display-3_text-white_text-center": "<h1 class=\"my-heading display-3 text-white text-center\">[]</h1>",
"h1__mt-4": "<h1 class=\"my-heading mt-4\">[]</h1>",
"h1__mt-5": "<h1 class=\"my-heading mt-5\">[]</h1>",
"h1__mt-5_kakabum": "<h1 class=\"my-heading mt-5 kakabum\">[]</h1>",
"h1__my-4": "<h1 class=\"my-heading my-4\">[]</h1>",
"h2": "<h2>[]</h2>",
"h2__card-title": "<h2>[]</h2>",
"h2__mt-4": "<h2>[]</h2>",
"h2__my-4": "<h2>[]</h2>"
}
Instead of desired:
{
"h1": "<h1 class=\"my-heading\">[]</h1>",
"h1__display-3": "<h1 class=\"my-heading display-3\">[]</h1>",
"h1__display-3_text-white_text-center": "<h1 class=\"my-heading display-3 text-white text-center\">[]</h1>",
"h1__mt-4": "<h1 class=\"my-heading mt-4\">[]</h1>",
"h1__mt-5": "<h1 class=\"my-heading mt-5\">[]</h1>",
"h1__mt-5_kakabum": "<h1 class=\"my-heading mt-5 kakabum\">[]</h1>",
"h1__my-4": "<h1 class=\"my-heading my-4\">[]</h1>",
"h2": "<h2>[]</h2>",
"h2__card-title": "<h2 class=\"card-title\">[]</h2>",
"h2__mt-4": "<h2 class=\"mt-4\">[]</h2>",
"h2__my-4": "<h2 class=\"my-4\">[]</h2>"
}
^notice: No class attribute as per d1 for "h2": "<h2>[]</h2>",
but because key has '__'
, class pattern has been inserted "h2__card-title": "<h2 class=\"card-title\">[]</h2>"
.
I'm missing the step between res2 and res3, could someone help me out?