简体   繁体   English

将品脱单位格式化为短格式符号

[英]Format Pint unit as short-form symbol

Say I have an arbitrary Pint quantity q .假设我有一个任意品脱数量q Is there a way to display its units in symbol short form, instead of as a full-length word?有没有办法以符号短格式显示其单位,而不是作为全长单词?

In other words, how would I code unit_symbol() such that it returns "m", not "meter";换句话说,我将如何对unit_symbol()进行编码,使其返回“m”,而不是“meter”; "kg" not "kilogram"; “公斤”不是“公斤”; etc.? ETC。? Is there a way to retrieve the short-form unit symbol that is synonym with the quantity's current unit?有没有办法检索与数量的当前单位同义的短格式单位符号?

import pint 
ureg = pint.UnitRegistry()
Q_ = ureg.Quantity

def unit_symbol(q: pint.Quantity) -> str:
    # Intended to return "m", not "meter"
    # "kg" not "kilogram"
    # etc.
    # ???
    return q.units  # returns long-form unit, "meter", "kilogram" etc. :-(
    
q = Q_(42, ureg.m)
print(unit_symbol(q))  # "meter"... whereas I would like "m"

The above obviously fails to achieve this;以上显然无法实现这一点; it returns the long-form unit.它返回长格式单元。

You can use '~' as a spec for the unit formatting:您可以使用'~'作为单位格式的规范:

q = Q_(42, "m") / Q_(1, "second")

print(format(q, '~'))  # 42.0 m / s
print(format(q.u, '~'))  # m / s

This feature is apparently undocumented, but can be inferred from the source code for Unit.__format__ (search for "~" on that page to quickly navigate to the relevant piece of code).此功能显然没有记录,但可以从Unit.__format__源代码中推断出来(在该页面上搜索"~"以快速导航到相关代码段)。

I found UnitRegistry.get_symbol() ,我找到UnitRegistry.get_symbol()

ureg.get_symbol(str(q.units))  # "m"

but it seems a bit clunky: converting unit to string, then parsing that string again...但它似乎有点笨拙:将单位转换为字符串,然后再次解析该字符串......

Also this fails for composite units eg这对于复合单元也失败,例如

q = Q_(42, "m") / Q_(1, "second")
ureg.get_symbol(str(q.units))  
# UndefinedUnitError: 'meter / second' is not defined in the unit registry

Use ureg.default_format = '~' if you want the short notation by default.如果您希望默认使用短符号,请使用ureg.default_format = '~' These are also valid options for short units: ~L (LaTeX), ~H (HTML) and ~P (Pretty print).这些也是短单位的有效选项: ~L (LaTeX)、 ~H (HTML)和~P (Pretty print)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM