在Python中将字符串转换为“unit”对象 [英] Casting string to 'unit' object in Python

查看:128
本文介绍了在Python中将字符串转换为“unit”对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题中,单位是指用于物理量的计量单位。



希望安全地解析包含物理量(例如23 kg)的不受信任的用户输入字符串。我想使用可用于Python的一个包(例如 Unum ),因为它们负责单位之间的转换,简化数学表达式中包含的单位,减少到基本单位,但我找不到一种方法将字符串转换为一个对象(上述包),而不是使用 eval(),这似乎不安全。



例如,假设 kg cm 绑定到 Unum 包对象并引用千克和厘米单位,我需要一个能够从字符串返回一个 Unum 包对象的函数,例如:



cast_to_unit(100 kg / cm)



100 kg / cm.asUnit()


  1. 有没有办法从一个
    提到的包中获取这样的功能?如果没有,

  2. 有没有办法安全地使用
    eval()?如果没有,

  3. 是否有其他任何软件包(即使不在
    Python中)具有此类功能?


解决方案

快速浏览 Unum 文档,您似乎应该可以使用 eval

  from unum.units import *#加载多个公共单位。 
distance = 100 * m
time = eval('9.683 * s')
speed = distance / time
print(speed)

如果你这样做,请务必阅读 eval 可以传递本地和全局映射,以限制命名空间访问,使其更安全 - 尤其是如果您计划将此代码发布到外部世界。你可能还需要检查下划线( _ )的字符串,并且不允许将它们传递给 eval






正如kindall所说,导入 * 好风格。这里是一个稍微更安全的选择,它避免从 *
$ b import unum.units
safe_dict = dict((x,y)for x,y in unum.units .__ dict __。items()if'__'not in x)
safe_dict ['__ builtins__'] = None

def convert(s):
如果'__'在s:
raise ValueError(不会这样做,下划线...它是不安全的)$ b $注意,我剪下了 __ 在此帖子中提倡的方法


In this question "unit(s)" refers to "unit(s) of measure" used in physical quantities.

I want to safely parse an untrusted user input string containing physical quantities (e.g. '23 kg'). I'd like to use one of the packages available for Python (like Unum or Quantities), because they take care of conversions between units, simplification of units contained in mathematical expression, reduction to base units, but I could not find a way to convert a string to an object (of the aforementioned packages) other than using eval(), which seems unsafe.

For example, assuming that kg and cm are bound to Unum package objects and refer to the kilogram and centimetre units, I need a function capable of returning an Unum package object from a string, something like:

cast_to_unit("100 kg/cm")

or

"100 kg/cm".asUnit()

  1. Is there a way to obtain such functionality from one the mentioned packages? And if not,
  2. Is there a way to safely use eval()? And if not,
  3. Is there any other package (even not in Python) having such functionality?

解决方案

Taking a quick look at Unum's documentation, it appears that you should be able to do something like this with eval:

from unum.units import * # Load a number of common units.
distance = 100*m
time = eval('9.683*s')
speed = distance / time
print(speed)

If you do this though, make sure that you read the documentation on eval and how you can pass local and global mappings in order to restrict the namespace access to make it safer -- especially if you ever plan on releasing this code to the outside world. You'll probably also want to check the strings for underscores (_) and not allow those to be passed to eval.


As noted by kindall, importing * is usually not good style. Here's a slightly more safe alternative which avoids importing from *:

import unum.units
safe_dict = dict((x,y) for x,y in unum.units.__dict__.items() if '__' not in x)
safe_dict['__builtins__'] = None

def convert(s):
    if '__' in s:
       raise ValueError("Won't do this with underscores...it's unsafe")
    return eval(s,safe_dict)

Note that I cut out the __ methods as advocated in this post

这篇关于在Python中将字符串转换为“unit”对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆