gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:01:43 25 4
gpt4 key购买 nike

我认为标题已经说明了一切。我有一个字符串,我试图将其插入 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:我使用的 Unicode 字符串 ref Unicode Character 'SUPERSCRIPT THREE' (U+00B3) ,以防万一其他人需要它。

第一步根据字符串中间的空格将字符串分成两部分。第二步,将所有字符从 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)
>>>

结果:

enter image description here

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com