gpt4 book ai didi

python - 重新分组 : Is it possible to specify the value type?

转载 作者:行者123 更新时间:2023-12-01 13:13:03 25 4
gpt4 key购买 nike

我有以下正则表达式来分解需要作为字典返回的子元素中的轮胎规范。它的数字元素需要作为 int 返回。

这是一个输入示例:

tyre_specs = '255/45W17'

所需的输出:
tyre_details = {'width': 255, 'profile': 45, 'rating': 'W', 'rim': 17}

我使用带有命名捕获的正则表达式模式捕获每个元素,它们与所需的输出字典键匹配。然后我使用 groupdict 来生成我的输出字典。但是,所有值都是字符串。所以我需要进一步处理相关值以将它们转换为 int。

我的功能,见下文,有效。但是我想知道是否有更好的方法来做到这一点。例如,有没有办法强制执行某些特定匹配组的类型?

如果不是,这种方法是“pythonic”吗?

这是我的功能
import re

def tyre_details(tyre_size):
pattern = r'(?P<width>\d{3})\/(?P<profile>\d{2})(?P<rating>[A-Z]{1,2})(?P<rim>\d{2})'
try:
details = re.match(pattern, tyre_size).groupdict()
except AttributeError:
raise ValueError('Input does not conform to the usual tyre size nomenclature "Width/ProfileRatingRim"')

int_keys = set('width profile rim'.split())
for key in int_keys:
details[key] = int(details[key])
return details

编辑:
  • 添加了输入字符串不匹配时的处理异常。我将此作为值错误提出
  • 将要转换的键定义为集合而不是列表。
  • 删除了多余的 try/except 子句。
  • 最佳答案

    我会首先检查正则表达式是否匹配。如果是这样,那么 match.groups()可以直接解引用到变量中并用于构建最终的字典对象:

    import re

    def tyre_details(tyre_size):
    pattern = r'(\d{3})/(\d{2})([A-Z]{1,2})(\d{2})'
    m = re.match(pattern, tyre_size)
    details = {}
    if m:
    width, profile, rating, rim = m.groups()
    details = {"width": int(width), "profile": int(profile), "rating": rating, "rim": int(rim)}
    return details

    tyre_specs = '255/45W17'
    print( tyre_details(tyre_specs) )
    # => {'width': 255, 'profile': 45, 'rating': 'W', 'rim': 17}

    Python demo

    使用这种方法不需要命名组,您也不需要任何 try/except或类型转换时的其他检查 strint因为有问题的组只匹配数字,请参阅 (\d{3}) , (\d{2})(\d{2}) .

    如果您需要完整的字符串匹配,请替换 re.matchre.fullmatch ,如果匹配可以出现在字符串中的任何位置,请使用 re.search .

    备注 /不是任何特殊的正则表达式元字符,不要在模式中对其进行转义。

    关于python - 重新分组 : Is it possible to specify the value type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58835942/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com