使用Python将HTML转换为Ascii并返回的问题(html2text,textile)

时间:2019-07-15 14:12:07

标签: python html python-3.x formatting textile

我正在尝试将HTML文本转换为ASCII,进行翻译,然后再将其转换回HTML。

到目前为止,在测试脚本的基本结构时,我遇到了一个问题,纺织品无法将所有内容都转换回可读的HTML格式。

我认为这是由于缩进的输出所致,这使纺织品难以读取-但我被困在这里。

h = html2text.html2text('<p><strong>This is a test:</strong></p><ul><li>This text will be converted to ascii</li><li>and then&nbsp;<strong>translated</strong></li><li>and lastly converted back to HTML</li></ul>')
print(h)

print('------------Converting Back to HTML-----------------------------')


html = textile.textile( h ) 
print (html)

这是我得到的输出:

**This is a test:**

  * This text will be converted to ascii
  * and then  **translated**
  * and lastly converted back to HTML


------------Converting Back to HTML-----------------------------
    <p><b>This is a test:</b></p>

  * This text will be converted to ascii
  * and then  <b>translated</b>
  * and lastly converted back to <span class="caps">HTML</span>

我应该补充一点,将来我将使用Excel工作表中的HTML数据。

2 个答案:

答案 0 :(得分:1)

要注意的重要一件事是html2text将HTML转换为 markdown 而不是纺织,因此当产生正确的结果时,这有点巧合。我建议您寻找一个能够理解您所使用的标记语言的转换器。 Pandoc可以在几乎任何格式之间进行转换。

也就是说,您是正确的,就是缩进是导致列表出现问题的原因,可以通过在h上进行简单的文本替换来解决:

html = textile.textile(h.replace("\n  *", "\n*"))

答案 1 :(得分:0)

有两种方法。

第一种方式:

def html_encode(html):
    return html.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')

第二种方式:

def html_decode(s):
    htmlCodes = (
            ("'", '&#39;'),
            ('"', '&quot;'),
            ('>', '&gt;'),
            ('<', '&lt;'),
            ('&', '&amp;')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s

用法:

examplehtml = "<html><head></head></html>"
examplehtml2 = "&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;/html&gt;"

print(html_encode(examplehtml))
print(html_decode(examplehtml))