如何提取具有数学符号的HTML生成数据,并将其准确转换为文本格式?

2024-09-27 00:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用beautifulsoup从html中提取文本。 html代码的格式如下。 代码使用数学标记生成文本。你知道吗

“”“

<p>

 <span class="aps-inline-formula">
  <math display="inline" xmlns="http://www.w3.org/1998/Math/MathML">
   <mrow>
    <msub>
     <mi mathvariant="normal">
      Pt
     </mi>
     <mrow>
      <mo>
       (
      </mo>
      <mn>
       1
      </mn>
      <mo>
       −
      </mo>
      <mi>
       x
      </mi>
      <mo>
       )
      </mo>
     </mrow>
    </msub>
    <msub>
     <mi mathvariant="normal">
      Ru
     </mi>
     <mi>
      x
     </mi>
    </msub>
   </mrow>
  </math>
 </span>
 alloys in the presence of adsorbing oxygen. 
</p>

“”“ 此html在浏览器中生成数学公式(如下所示)

““ 将该方法应用于金属(111)表面的有序化和偏析 Pt公司 ( 1 − 十 ) 俄罗斯 十 “吸附氧存在下的合金”

我希望保持格式不变,使用python将数据转换为文本格式。 请给我一些建议。你知道吗


Tags: 代码文本pthtml格式inlinemathmo
1条回答
网友
1楼 · 发布于 2024-09-27 00:23:24

我在html中看不到“该方法应用于(111)表面的表面排序和分离”。但是考虑到这里的内容,您可以将html存储为字符串。你知道吗

输出:

>>> print (text)
Out[36]: '\n\n\n\n\n\n      Pt\n     \n\n\n       (\n      \n\n       1\n      \n\n       −\n      \n\n       x\n      \n\n       )\n      \n\n\n\n\n      Ru\n     \n\n      x\n     \n\n\n\n\n alloys in the presence of adsorbing oxygen. \n'

然后使用regex删除空格和新行:

import bs4
import re

html = '''<p>

 <span class="aps-inline-formula">
  <math display="inline" xmlns="http://www.w3.org/1998/Math/MathML">
   <mrow>
    <msub>
     <mi mathvariant="normal">
      Pt
     </mi>
     <mrow>
      <mo>
       (
      </mo>
      <mn>
       1
      </mn>
      <mo>
       −
      </mo>
      <mi>
       x
      </mi>
      <mo>
       )
      </mo>
     </mrow>
    </msub>
    <msub>
     <mi mathvariant="normal">
      Ru
     </mi>
     <mi>
      x
     </mi>
    </msub>
   </mrow>
  </math>
 </span>
 alloys in the presence of adsorbing oxygen. 
</p>'''


soup = bs4.BeautifulSoup(html, 'html.parser')  

text = soup.find('p').text

string =  re.sub('[ \n]+', ' ', text).strip()

输出:

>>> print (string)
Pt ( 1 − x ) Ru x alloys in the presence of adsorbing oxygen.

相关问题 更多 >

    热门问题