HTML 到 LaTex:如何使用 python 和 lxml 將 html 文件轉換為帶有自訂巨集的 LaTeX

HTML 到 LaTex:如何使用 python 和 lxml 將 html 文件轉換為帶有自訂巨集的 LaTeX

我想使用 python 獲取帶有一組已知標籤的 html5 文檔,並將它們轉換為 LaTeX,以便使用自訂的 LaTeX 巨集進行高品質列印。

答案1

我查看了許多工具,最終選擇了帶有遞歸函數的 lxml,將 html 標籤映射到 LaTeX 標記。它為您提供了一個輕鬆使用 Python 定義映射的位置。我相信我是根據書中的一個例子進行工作的,Python 網路程式設計基礎

這是 Python 2.7 中一個最小的工作範例:

# convert html document to LaTeX
import lxml.html # http://lxml.de/lxmlhtml.html
from lxml import etree
from io import StringIO, BytesIO

def html2latex(el): # fill in this function to catch and convert html tags
    result = []
    if el.text:
        result.append(el.text)
    for sel in el:
        if False: # get info
            print('tag',sel.tag)
            print('text',sel.text)
            print('tail',sel.tail)
            print('attrib',sel.attrib)
        if sel.tag in ["h1"]:
            result.append('\hmchapter{%s}' % html2latex(sel))
        elif sel.tag in ["td", "table"]:
            result.append("<%s>" % sel.tag)
            result.append(html2latex(sel))
            result.append("</%s>" % sel.tag)
        elif sel.tag in ["span"]:  #
            for att in sel.attrib.keys():
                if att =='style':
                    if sel.attrib[att] == 'font-style:italic':
                        result.append(r'\textit{%s}' % (html2latex(sel)))
        else:
            result.append(html2latex(sel))
        if sel.tail:
            result.append(sel.tail)
    return "".join(result)

def main():
    # must be unicode or lxml parse crashes
    html = u'''
<!DOCTYPE html>
    <html>
  <head>
    <title></title>
  </head>
<body >
  <h1 class="hmchapter" data-hmvarbodychaptertitle = "My title">My title</h1>
  text <span style="font-style:italic">in a specific context</span> and more.
</body>
</html>
'''
    parser = etree.HTMLParser()
    tree   = etree.parse(StringIO(html), parser) # expects a file, use StringIO for string
    root = tree.getroot()
    latex = html2latex(root)
    print latex

if __name__ == '__main__':
    main()

列印:

\hmchapter{My title}
text \textit{in a specific context} and more.

相關內容