[Python] Having an issue with converting imperial to metric in Python

Discussão em 'Python' iniciado por Stack, Junho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm currently studying engineering and have a lot of books that are in imperial, when I work in metric. Therefore I was trying to write a function in Python that allows me to paste a line of text, which automatically detects the imperial units in said text, then stores it in a dict so I can loop through said dict to convert it to metric.

    I thought the way of doing this, was by using a regex function. However it seems to convert ft/sec² or ft/sec to ft as well, before it gets a chance to "see" the /sec² or /sec part of the unit I'm assuming. If anyone knows a better way to check this than with a regex, I'm open to suggestions!

    I've provided a snippet of my code below:


    def extractUnitsFromText(text):
    pattern = r'(?P<value>\d+\.?\d*)[-\s]*?(?P<unit>(?:ft/sec²|ft/s²|ft/s2|ft/sec|ft/s|in(?:ches)?\.?|ft\.?|feet|lb/ft|pounds?|lb(?:\s*/\s*ft)?|slug(?:s)?)(?:\^[\d]+)?)'
    matches = re.finditer(pattern, text)

    units_dict = defaultdict(list)

    for match in matches:
    value = float(match.group('value'))
    unit = match.group('unit').strip().lower()

    unit = unit.replace('lbs', 'lb').replace('in.', 'in')
    units_dict[unit].append(value)

    return dict(units_dict)```

    Continue reading...

Compartilhe esta Página