【问题标题】:Converter of the unit of measurement found in the string Python在字符串 Python 中找到的测量单位的转换器
【发布时间】:2020-08-01 04:51:09
【问题描述】:

大家好
我来这里是因为我需要你的帮助:)
我需要找到字符串测量单位并进行转换。
就我而言,我在寻找克和毫克。

示例:
“文本文本...使用 0.0075 g”或
“文本文本...使用 0.0075g”或
“文本文本...使用 0,0075g”

我有正则表达式来查找度量单位: re.findall(r"(\d*\.?(?:.|,)\d+)\s*(lbs?|g)" ,text)

但我不确定如何获取这段匹配的文本,检查它们是克还是毫克
在克的情况下乘以 1000 并修改字符串以获得:
“text text .... use 75mg”

非常感谢您的帮助和解释。

【问题讨论】:

  • 一个简单的规则可以是 if

标签: python-3.x units-of-measurement


【解决方案1】:

您可以使用拆分方法来隔离您感兴趣的内容:

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)

我放了很多“步骤”变量,以便您轻松理解。

两个警告:

  • “使用 0.75 克”不行 -> 使用点作为昏迷“使用 0.75 克”

  • “使用 0.75 克”不行 -> 不要放空格“使用 0.75 克”

【讨论】:

  • Its working great but assuming when 0.0075g is at the end of the string. In case 'random text text text use 0.0075g some text' does not work properly and I dont 知道如何解决它。但是我已经修复了你写的弱点(数字和 g 之间的逗号和空格):)
  • 我用它来查找号码:import re string = "Random text word 0.0075g next text end." pattern = re.search(r"(\d*\.?\d+)\s*(g)", string) if pattern: numer = pattern.group() numer1 = (numer.split("g")) print(numer1[0]) 然后我用了你写的,它工作正常。有什么建议吗?
  • 有一些方法可以将已知字符串查找到列表中(您使用拆分获得的列表),但如果您不知道确切的字符串,那可能会很困难......如果您的程序有效这是必不可少的!
  • 感谢帮助 :)
【解决方案2】:

你可以只使用“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)")]

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2014-05-23
    • 2019-08-06
    • 2012-05-16
    • 2019-10-29
    • 2023-02-05
    相关资源
    最近更新 更多