Python用匹配对值替换正则表达式匹配

2024-10-02 22:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个别名列表,它与运行时可用的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专业人士如何以简洁的方式编写枚举表达式?你知道吗

谢谢,干杯!你知道吗


Tags: the代码reid列表valuelinebob
2条回答

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

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!

如果您将在代码中直接使用这些别名(而不仅仅是从数据结构引用),那么Enum是一个很好的方法:

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)

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

    @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布满他们的代码呢?最好将替换文本与枚举成员名称分开,使用^{}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参见this answer了解标准Enum用法。你知道吗

披露:我是Python stdlib ^{}^{} backportAdvanced Enumeration (^{})库的作者。你知道吗

相关问题 更多 >