Reputation: 35
Hi All
I came here because I need your help :)
I need to find in string units of measurement and convert them.
In my case I looking for grams and milligrams.
Example:
"text text ... use 0.0075 g" or
"text text ... use 0.0075g" or
"text text ... use 0,0075g"
I have regex to find units of measurement:
re.findall(r"(\d*\.?(?:.|,)\d+)\s*(lbs?|g)" ,text)
But I'm not sure how to take this piece of matching text, check if they are grams or milligrams
and in the case of grams multiply by 1000 and modify the string to get:
"text text .... use 75mg"
I would be very grateful for your help and and explanation.
Upvotes: 1
Views: 1461
Reputation:
You can just use "quantulum3", it has a decent parser, after parsing you can check the name of the unit and multiply accordingly.
from quantulum3 import parser
parser.parse("random text text text use 0.0075g")
#[Quantity(0.0075, "Unit(name="gram", entity=Entity("mass"), uri=Gram)")]
Upvotes: 1
Reputation: 514
You can use split method to isolate what is interesting for you :
string = "random text text text use 0.0075g"
check = string.split("m")
print(check)
if check[len(check)-1] == "g":
print("already in mg")
else:
step = string.split(" ")
step2 = step[len(step)-1].split("mg")
newstring = " ".join(step)
step3 = step2[0].split("g")
step4 = float(step3[0])
newstring = newstring.replace(step2[0], str(step4*10000)+"mg")
print(newstring)
I put many "step" variables so you can understand easily.
TWO WARNINGS:
"use 0,75g" isn't ok -> use a point as a coma "use 0.75g"
"use 0.75 g" isn't ok -> don't put spaces "use 0.75g"
Upvotes: 1