Python,根据输入字符串的格式和内容运行函数

发布于 2024-10-08 00:08:28 字数 343 浏览 0 评论 0原文

我想我应该尝试编写一种测量单位转换的东西只是为了练习。 我希望它的工作方式是向用户提供单个输入提示,并根据字符串运行适当的函数。

我只是想知道告诉天气的最好方法是什么,字符串的格式如下:

数字单位

示例:30厘米英寸(这将运行名为的函数cmtoinch 传递数字 30 作为参数)。

我还需要能够区分哪个单位在另一个单位前面,因为“30 厘米英寸”会给出与“30 英寸厘米”不同的结果。

我想将每个单元的名称放入一个列表中,但我不知道如何将字符串与列表进行比较以查看它是否至少包含两个值。

I thought I'd try writing a kind of a measurements units conversion thingy just for practice.
I would like it to work in a way that the user would be given a single input prompt and it would run the appropriate function based on the string.

I'm just wondering what would be the best way to tell weather the string is formatted like this:

number unit unit

example: 30 cm inch (this would run the function named cmtoinch passing the number 30 as an arguement).

I would also need to be able to tell which unit is in front of the other cause "30 cm inch" would give different results then "30 inch cm".

I was thinking I'd put the names of each unit into a list, but I don't know how to compare a string to the list to see if it contains at least two of the values.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

将军与妓 2024-10-15 00:08:28

在字符串上使用 .split() 将其分解为单词(然后您可以将第一个单词重新解释为 intfloat 为合适的)。生成的列表将与输入字符串的顺序相同,因此您可以依次查看每个元素并根据单位参考列表进行检查。

为每个转换创建一个单独的函数可能不是您想要做的。相反,将输入转换为某种通用单位,然后从通用单位转换为所需的输出单位。为此,我们将每个单位与一个转换因子相关联;我们第一次乘法,第二次除法。

为了在单位名称和转换值之间建立关联,我们使用dict。这让我们可以通过插入名称直接查找转换值。

conversion_rates = {
    'in': 2.54, # 2.54 inches in a centimetre
    'cm': 1.00, # this is our reference unit
    'sun': 3.03 # a traditional Japanese unit of measurement
}

# raises ValueError if the number of words in the input is wrong
amount, original_unit, final_unit = line.split()

# raises ValueError if the amount is not formatted as a floating-point number
amount = float(amount)

# Now we do the conversion.
# raises KeyError if either unit is not found in the dict.
result = amount * conversion_rates[original_unit] / conversion_rates[final_unit]

Use .split() on the string to break it into words (then you can re-interpret the first one as an int or float as appropriate). The resulting list will be in the same order as the input string, so you can look at each element in turn and check it against your reference list of units.

Making a separate function for each conversion is probably not what you want to do. Instead, translate the input into some common unit, and then translate from the common unit to the desired output unit. To do this, we associate each unit with a single conversion factor; we multiply the first time, and divide the second time.

To make the association between unit names and conversion values, we use a dict. This lets us look up the conversion value directly by plugging in the name.

conversion_rates = {
    'in': 2.54, # 2.54 inches in a centimetre
    'cm': 1.00, # this is our reference unit
    'sun': 3.03 # a traditional Japanese unit of measurement
}

# raises ValueError if the number of words in the input is wrong
amount, original_unit, final_unit = line.split()

# raises ValueError if the amount is not formatted as a floating-point number
amount = float(amount)

# Now we do the conversion.
# raises KeyError if either unit is not found in the dict.
result = amount * conversion_rates[original_unit] / conversion_rates[final_unit]
暮倦 2024-10-15 00:08:28

根据此代码的组织,您可能需要使用 globals().__dict__getattr(obj)这里。我的示例使用 globals()

def cmtoinch(x):
  return x / 2.54

def inchtocm(x):
  return x * 2.54

def convert(input):
  num, unit1, unit2 = input.split()
  func = unit1 + "to" + unit2
  if func in globals():
    return globals()[func](float(num))
  else:
    raise NotImplementedException()

Depending on the organization of this code, you may want to use globals(), <modulename>.__dict__, or getattr(obj) here. My example uses globals().

def cmtoinch(x):
  return x / 2.54

def inchtocm(x):
  return x * 2.54

def convert(input):
  num, unit1, unit2 = input.split()
  func = unit1 + "to" + unit2
  if func in globals():
    return globals()[func](float(num))
  else:
    raise NotImplementedException()
压抑⊿情绪 2024-10-15 00:08:28

您可以使用字典(映射),并利用使用元组作为键的事实。

#!/usr/bin/python2

import sys

def inch2cm(inches):
    return inches * 2.54

def cm2inch(cm):
    return cm / 2.54


DISPATCH_TABLE = {
    ("in", "cm"): inch2cm,
    ("cm", "in"): cm2inch,
}

def converter(argv):
    """converter <value> <from unit> <to unit>
    """
    try:
        value = float(argv[1])
        unit_from = argv[2]
        unit_to = argv[3]
    except (ValueError, IndexError), ex:
        print ex
        print converter__doc__
        return 2

    func = DISPATCH_TABLE[(unit_from.lower()[:2], unit_to.lower()[:2])]
    print func(value)

    return 0


sys.exit(converter(sys.argv))

并不是说这是进行单位转换的最佳方式,而只是调度功能的演示。

我比从 globals() 中选择更喜欢这个,因为它更明确、更安全。

You can use a dictionary (mapping), and take advantage of the fact that you use tuples as keys.

#!/usr/bin/python2

import sys

def inch2cm(inches):
    return inches * 2.54

def cm2inch(cm):
    return cm / 2.54


DISPATCH_TABLE = {
    ("in", "cm"): inch2cm,
    ("cm", "in"): cm2inch,
}

def converter(argv):
    """converter <value> <from unit> <to unit>
    """
    try:
        value = float(argv[1])
        unit_from = argv[2]
        unit_to = argv[3]
    except (ValueError, IndexError), ex:
        print ex
        print converter__doc__
        return 2

    func = DISPATCH_TABLE[(unit_from.lower()[:2], unit_to.lower()[:2])]
    print func(value)

    return 0


sys.exit(converter(sys.argv))

Not saying this is the best way to do unit conversion, but just a demonstration of dispatching functions.

I like this better than picking from globals() because it's more explicit and safer.

小傻瓜 2024-10-15 00:08:28
{
    'cm': {
        'inch': cmtoinch,
        'microparsec': cmtomicroparsec
    }
}
{
    'cm': {
        'inch': cmtoinch,
        'microparsec': cmtomicroparsec
    }
}
死开点丶别碍眼 2024-10-15 00:08:28

这怎么样?

class Translator():
    UNITS = [
        # length
        {
            "cm": 1.0,
            "inch": 2.54,
            "foot": 30.48,
            "rod": 502.92
        },
        # weight
        {
            "kg": 1.0,
            "pound": 0.454,
            "stone": 6.356
        },
        # liquid volume
        {
            "litre": 1.0,
            "pint": 0.473,
            "gallon": 3.785
        }
    ]

    def translate(self, val, unit1, unit2):
        for u in Translator.UNITS:
            if u.has_key(unit1) and u.has_key(unit2):
                return float(val) * u[unit1] / u[unit2]

        return "Can't convert from %s to %s" % (unit1, unit2)

    def translateString(self, str):
        args = str.split()
        if len(args)==3:
            return self.translate( float(args[0]), args[1], args[2] )
        else:
            return "Exactly three arguments required!"

def main():
    t = Translator()

    while True:
        inp = raw_input("Translate what? (hit Enter to quit) ")
        if len(inp) > 0:
            t.translateString(inp)
        else:
            break

How's this?

class Translator():
    UNITS = [
        # length
        {
            "cm": 1.0,
            "inch": 2.54,
            "foot": 30.48,
            "rod": 502.92
        },
        # weight
        {
            "kg": 1.0,
            "pound": 0.454,
            "stone": 6.356
        },
        # liquid volume
        {
            "litre": 1.0,
            "pint": 0.473,
            "gallon": 3.785
        }
    ]

    def translate(self, val, unit1, unit2):
        for u in Translator.UNITS:
            if u.has_key(unit1) and u.has_key(unit2):
                return float(val) * u[unit1] / u[unit2]

        return "Can't convert from %s to %s" % (unit1, unit2)

    def translateString(self, str):
        args = str.split()
        if len(args)==3:
            return self.translate( float(args[0]), args[1], args[2] )
        else:
            return "Exactly three arguments required!"

def main():
    t = Translator()

    while True:
        inp = raw_input("Translate what? (hit Enter to quit) ")
        if len(inp) > 0:
            t.translateString(inp)
        else:
            break
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文