在字符串 Python 中找到的度量单位的转换器
Converter of the unit of measurement found in the string Python
大家好
我来这里是因为我需要你的帮助:)
我需要在字符串中找到测量单位并进行转换。
就我而言,我正在寻找克和毫克。
示例:
"text text ... use 0.0075 g" 或
"text text ... use 0.0075g" 或
"text text ... use 0,0075g"
我有正则表达式来查找测量单位:
re.findall(r"(\d*\.?(?:.|,)\d+)\s*(lbs?|g)" ,text)
但是我不知道怎么取这段匹配的文字,看看是克还是毫克
在克的情况下乘以 1000 并修改字符串以获得:
"text text .... use 75mg"
非常感谢您的帮助和解释。
您可以使用 split 方法来分离您感兴趣的内容:
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)
我放了很多"step"个变量,方便大家理解。
两个警告:
"use 0,75g" 不行 -> 使用一个点作为彗差 "use 0.75g"
"use 0.75 g" 不行 -> 不要放空格 "use 0.75g"
你可以只使用“quantulum3”,它有一个不错的解析器,解析后你可以检查单位的名称并相应地相乘。
from quantulum3 import parser
parser.parse("random text text text use 0.0075g")
#[Quantity(0.0075, "Unit(name="gram", entity=Entity("mass"), uri=Gram)")]
大家好
我来这里是因为我需要你的帮助:)
我需要在字符串中找到测量单位并进行转换。
就我而言,我正在寻找克和毫克。
示例:
"text text ... use 0.0075 g" 或
"text text ... use 0.0075g" 或
"text text ... use 0,0075g"
我有正则表达式来查找测量单位:
re.findall(r"(\d*\.?(?:.|,)\d+)\s*(lbs?|g)" ,text)
但是我不知道怎么取这段匹配的文字,看看是克还是毫克
在克的情况下乘以 1000 并修改字符串以获得:
"text text .... use 75mg"
非常感谢您的帮助和解释。
您可以使用 split 方法来分离您感兴趣的内容:
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)
我放了很多"step"个变量,方便大家理解。
两个警告:
"use 0,75g" 不行 -> 使用一个点作为彗差 "use 0.75g"
"use 0.75 g" 不行 -> 不要放空格 "use 0.75g"
你可以只使用“quantulum3”,它有一个不错的解析器,解析后你可以检查单位的名称并相应地相乘。
from quantulum3 import parser
parser.parse("random text text text use 0.0075g")
#[Quantity(0.0075, "Unit(name="gram", entity=Entity("mass"), uri=Gram)")]