将选项卡式/缩进的Python字符串转换为HTML列表输出

时间:2018-05-21 20:25:43

标签: python html css python-2.7

我有以下字符串作为示例:

>>> a
'The Distribution as follows:\n\t\t- 71% as follows:\n\t\t\tfirst, to A;\n\t\t\tsecond, to B;\n\t\t\tthird, to C, D, and E as follows:\n\t\t\t\t- 15% to C\n\t\t\t\t- 85% to D and E.\n\t\t- 29% to F.'
>>> print a
The Distribution as follows:
    - 71% as follows:
        first, to A;
        second, to B;
        third, to C, D, and E as follows:
            - 15% to C
            - 85% to D and E.
    - 29% to F.

我需要将这样的字符串转换为HTML输出,如下所示:

<span style="display:block; font: 13px 'Times New Roman'">The Distribution as follows:<br>
<ul style="display:block; list-style-type:none; line-height: 17px; font: 13px 'Times New Roman';">
    <li>- 71% as follows:</li>
    <ul style="display:block; list-style-type:none; line-height: 17px; font: 13px 'Times New Roman';"> 
        <li>first, to A;</li>
        <li>second, to B;</li>
        <li>third, to C, D, and E as follows:</li>
        <ul style="display:block; list-style-type:none; line-height: 17px; font: 13px 'Times New Roman';">
            <li>- 15% to C</li>
            <li>- 85% to D and E.</li>
        </ul>
     </ul>
     <li>- 29% to F.</li>
     </ul>
</span>

CSS将单独定义,这是测试的临时解决方案。另外,我需要在第二级用实心子弹点替换破折号,在第三级用空心子弹点替换,依此类推,如果它们是分层的。例如:

- X% as follows:
    * Y% as follows:
        o Z% as follows:
            - A% as follows:

我有这个迭代,当我用动态<p>的{​​{1}}标签包裹每一行时,它曾经工作过;但是,我需要转换所有left-padding标记,其中此类列表项需要具有HTML列表元素。在某些情况下它不起作用,例如上面的例子,其中29%的行是第一个缩进的一部分(我的代码用前一行缩进它,因为它在结尾处写了<p>。它也没有解决我的破折号/实体子弹/空心子弹。

</ul>

当我处理所有边缘情况时,我无法帮助,但想知道是否有更容易的解决方案。我也不太了解HTML,所以对所有建议持开放态度。我不想使用外部(非内置)Python库。

0 个答案:

没有答案