在python中混合HTML-Latex解析器

时间:2019-07-01 09:12:27

标签: python html parsing latex

我想解析混合了html和Latex表达式的文本(后者在[...]或(...)之间给出)。 即,输入是以下形式的表达式:

<p>text1 <ul><li> text2 \(x=1\) </li></ul> text2 \[y=0\]</p> text3 <code>z=e</code>

鉴于这种输入,我想翻译以下文本:text1text2text3text4,使<code>...</code>之间的元素保持不变,\[...\]\(...\)

我正在考虑创建一个解析器,即一棵树,该树对应于给定输入的附加图像。

tree

  • 首先,我需要做所有的工作吗?

  • 第二,我想知道是否应该从头开始编写所有代码,或者是否可以 一些HTML parser之类的库。

1 个答案:

答案 0 :(得分:1)

我在评论中描述了一种可能的算法实现方式:

data = '''<p>text1 <ul><li> text2 \(x=1\) </li></ul> text3 \[y=0\]</p> text4 <code>z=e</code>'''

from bs4 import BeautifulSoup
import re

s = re.sub(r'\\\[', r'<bracket1>', data)
s = re.sub(r'\\\]', r'</bracket1>', s)
s = re.sub(r'\\\(', r'<bracket2>', s)
s = re.sub(r'\\\)', r'</bracket2>', s)

soup = BeautifulSoup('<mydata>' + s + '</mydata>', 'html.parser')

for t in soup.select(':not(bracket1):not(bracket2):not(code)'):
    for txt in t.find_all(text=True, recursive=False):
        if txt.strip():
            txt.replace_with("I've changed {}".format(txt))

s = str(soup)
s = re.sub(r'<bracket1>', r'\\[', s)
s = re.sub(r'</bracket1>', r'\\]', s)
s = re.sub(r'<bracket2>', r'\\(', s)
s = re.sub(r'</bracket2>', r'\\)', s)

print('Old data:', data)
print('New data:', ''.join(str(t) for t in BeautifulSoup(s, 'html.parser').mydata.contents))

打印:

Old data: <p>text1 <ul><li> text2 \(x=1\) </li></ul> text3 \[y=0\]</p> text4 <code>z=e</code>
New data: <p>I've changed text1 <ul><li>I've changed  text2 \(x=1\) </li></ul>I've changed  text3 \[y=0\]</p>I've changed  text4 <code>z=e</code>