如何刮擦具有数学符号HTML生成的数据并将其精确化为文本格式



我正在尝试使用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 - X)ruX 在吸附氧气的情况下合金"

我想保持格式,因为它使用Python将数据纳入文本格式。请给我一些建议。

我看不到"该方法应用于HTML中的(111)表面的表面排序和隔离"。但是,鉴于这里的内容,您可以将HTML存储为字符串。

将提供输出:

>>> print (text)
Out[36]: 'nnnnnn      Ptn     nnn       (n      nn       1n      nn       −n      nn       xn      nn       )n      nnnnn      Run     nn      xn     nnnnn 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.

最新更新