Python-将正则表达式匹配替换为匹配对值

时间:2018-08-07 18:45:50

标签: python regex enumeration

比方说,我有一个别名列表,这些别名与运行时可用的5位代码相关:

aliasPairs = [(12345,'bob'),(23456,'jon'),(34567,'jack'),(45678,'jill'),(89012,'steph')]

我想找到一种简洁的表达方式:用匹配的别名替换行中的ID,例如:

line = "hey there 12345!"
line = re.sub('\d{5}', value in the aliasPairs which matches the ID, line)
print line

应输出:

hey there bob!

Python专业人员如何以简洁的方式编写枚举表达式?

谢谢和欢呼!

2 个答案:

答案 0 :(得分:3)

当您对两类数据(例如五位数字代码和别名)进行一对一映射时,请考虑使用字典。然后,根据其代码,很容易访问任何特定的别名:

import re

aliases = {
    "12345":"bob",
    "23456":"jon",
    "34567":"jack",
    "45678":"jill",
    "89012":"steph"
}

line = "hey there 12345!"
line = re.sub('\d{5}', lambda v: aliases[v.group()], line)
print(line)

结果:

hey there bob!

答案 1 :(得分:1)

如果您将直接在代码中使用这些别名(而不仅仅是从数据结构中引用),那么Enum是行之有效的 1

from enum import Enum

class Alias(Enum):
    bob = 12345
    jon = 23456
    jack = 34567
    jill = 45678
    steph = 89012

然后使用re如下:

line = "hey there 12345!"
line = re.sub('\d{5}', lambda v: Alias(int(v.group()).name, line)

您还可以使用以下方法将该行为直接添加到Alias Enum

    @classmethod
    def sub(cls, line):
        return re.sub('\d{5}', lambda v: cls(int(v.group())).name, line)

并在使用中:

Alias.sub("hey there 12345!")

当然,"bob"应该大写,但是谁愿意在整个代码中使用Alias.Bob?最好将替换文本与Enum成员名称分开,使用aenum 2

可以更轻松地完成工作。
from aenum import Enum
import re

class Alias(Enum):
    _init_ = 'value text'
    bob = 12345, 'Bob'
    jon = 23456, 'Jon'
    jack = 34567, 'Jack'
    jill = 45678, 'Jill'
    steph = 89012, 'Steph'
    @classmethod
    def sub(cls, line):
        return re.sub('\d{5}', lambda v: cls(int(v.group())).text, line)

Alias.sub('hey there 34567!')

1 有关标准Enum的用法,请参见this answer

2 披露:我是Python stdlib Enumenum34 backportAdvanced Enumeration (aenum)库的作者。

相关问题