I'm trying to parse strings in Python, looking for scientific values and units. I want to retrieve them in order to convert them to some other units.
I'm using the library unit-parse (based on pint) but it has trouble understanding this example : 12.5g/100ml
.
I managed a workaround : replacing g/100mL
in the string by another word (stuff
for example in the code below) and using this word as a new unit (equivalent to (g/l) * 10
)
My code:
import logging
import pint
u = pint.UnitRegistry()
U = Unit = u.Unit
Q = Quantity = u.Quantity
from unit_parse import parser, logger, config
def display(text):
text = text.replace(" ", "") # Suppress spaces.
result = parser(text)
print(f"RESULT = {result}")
print(f"VALUE = {result.m}")
print(f"UNIT = {result.u}")
print(f"to g/l = {result.to('g/L')}")
print(f"to g/ml = {result.to('g/ml')}")
print(f"to stuff = {result.to('stuff')}")
def main():
u.define('stuff = (g/l) * 10')
logger.setLevel(logging.INFO)
more_last_minute_sub = [["g/100mL", "stuff"]] # [bad text/regex, new text]
config.last_minute_sub += more_last_minute_sub # Here we are adding to the existing list of units
text = ("12.5g / 100mL")
Is there a better way to do this ? Or should I stick to this workaround ? Is there a better library to use ?