Obecnie używam Pint do obsługi jednostek i konwersji jednostek. To wydaje się działać dobrze dla jednostek, które są już zdefiniowane w Kufel, na przykładJak definiować i używać procentu w kuflach:
>>> import pint
>>> ureg = pint.UnitRegistry()
>>> Q = ureg.Quantity
>>> a = Q(5, 'm/s')
>>> a
<Quantity(5, 'meter/second')>
>>> a.to('ft/s')
<Quantity(16.404199475065617, 'foot/second')>
Próbowałem define my own units, które stanowią procent. Jeśli chodzi o konwersje jednostek, procent jest po prostu 100-krotnością frakcji bezwymiarowej, tak ją zdefiniowałem.
>>> ureg.define('percent = dimensionless * 100 = pct')
>>> a = Q(5, 'pct')
>>> a
<Quantity(5, 'percent')>
Jednak nie wydaje się przekształcić w tę iz powrotem pomiędzy frakcją ('dimensionless'
) i 'pct'
.
>>> a.to('dimensionless')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
a.to('dimensionless')
File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\quantity.py", line 263, in to
magnitude = self._convert_magnitude_not_inplace(other, *contexts, **ctx_kwargs)
File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\quantity.py", line 231, in _convert_magnitude_not_inplace
return self._REGISTRY.convert(self._magnitude, self._units, other)
File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 1026, in convert
return self._convert(value, src, dst, inplace)
File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 1042, in _convert
src_dim = self._get_dimensionality(src)
File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 813, in _get_dimensionality
self._get_dimensionality_recurse(input_units, 1.0, accumulator)
File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 837, in _get_dimensionality_recurse
self._get_dimensionality_recurse(reg.reference, exp2, accumulator)
File "C:\Python35\python-3.5.1.amd64\lib\site-packages\pint\unit.py", line 835, in _get_dimensionality_recurse
reg = self._units[self.get_name(key)]
KeyError: ''
Co zasadniczo chciałbym zrobić, to móc przekonwertować między np. "0,73" i "73%". Jak mogę zdefiniować i używać takiej jednostki?
użyłem 'z pint.converters importować ScaleConverter' – nowox
Od kufel 0,8 to wydaje się, że usunęli 'pint.unit.ScaleConverter', ale' pint.converters.ScaleConverter' jest nadal dostępny, więc reszta rozwiązania jest nadal ważna. – CoryKramer