我认为标题说明了一切。我有一个试图将其插入Beautiful Soup文档中的字符串。我找到了Exponent notation,但不知道是否以及如何将其应用于我的案子。

工作示例:

#!/usr/bin/python

from bs4 import BeautifulSoup

html_sample = """
<!DOCTYPE html>
<html><head lang="en"><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body>
<div class="date">LAST UPDATE</div>
</body>
</html>
"""

si_unit = '3 m3/s'

soup = BeautifulSoup(html_sample)
forecast = soup.find("div", {"class": "date"})
forecast.string = si_unit
print(soup.prettify())


输出样本:

<!DOCTYPE html>
<html>
 <head lang="en">
  <meta charset="utf-8">
   <meta content="width=device-width, initial-scale=1" name="viewport"/>
  </meta>
 </head>
 <body>
  <div class="date">
   3 m3/s
  </div>
 </body>
</html>


我的问题是si单位不是指数的。如何将m(3)/ s值转换/打印为指数?

有人知道要进行此棘手的操作吗?
预先感谢您的时间和精力。

更新:按照给定的示例代码将输出从2 m3 / s修改为3 m3 / s。

更新2:感谢jumbopap,为我的问题添加了有效的解决方案。

更新3:修改解决方案。

更新4:我使用ref Unicode Character 'SUPERSCRIPT THREE' (U+00B3)的Unicode字符串,以防万一其他人需要它。

第一步根据字符串中间的空格将字符串分为两部分。第二步,将所有字符从si单元部分(我们要修改指数的部分)中拆分为一个列表。
第三,将所有字符连接到一个新字符串中,以将其推送到BeautifulSoup中。

工作代码示例:

from bs4 import BeautifulSoup

html_sample = """
<!DOCTYPE html>
<html><head lang="en"><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body>
<div class="date">LAST UPDATE</div>
</body>
</html>
"""

si_unit = '3 m3/s'
unit, si_unit = si_unit.split()
si_unit_list = list(si_unit)

soup = BeautifulSoup(html_sample, 'html.parser')
forecast = soup.find("div", {"class": "date"})
forecast.string = unit + si_unit_list[0] + u"\u00B3" + si_unit_list[2] + si_unit_list[3]
print(soup.prettify())


和产生的输出:

<!DOCTYPE html>
<html>
 <head lang="en">
  <meta charset="utf-8">
   <meta content="width=device-width, initial-scale=1" name="viewport"/>
  </meta>
 </head>
 <body>
  <div class="date">
   3m³/s
  </div>
 </body>
</html>

最佳答案

在字符串中使用superscript 3 character。您可以将Beautiful soup作为HTML进行美化并输出。

>>> html = '<p>2³</p>'
>>> soup = BeautifulSoup.BeautifulSoup(html, 'html.parser')
>>> out = soup.prettify(formatter="html")
>>> file('tmp.html', 'wb').write(out)
>>>


结果:

python - 如何在BeautifulSoup上打印指数单位-LMLPHP

关于python - 如何在BeautifulSoup上打印指数单位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34814168/

10-13 08:39