如何用他们的名字替换部门标识符?-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

如何用他们的名字替换部门标识符?

一码平川MACHEL 2019-01-22 11:53:17 799

我有一点问题,我有几个城市的部门标识符,我想用其部门替换每个城市,最后我只有部门。我怎么能用python做到这一点?

以下是输入样本(具有已识别部门的城市):

Blois et arrondissement (41)
Loiret Ouest (45)
Agglomération de Tours (37)
Nord de l’Indre et Loire (37)
Vendôme et arrondissement (41)
Loiret Est (45)
Lochois (37)
Romorantin et arrondissement (41)
我想只获得部门:

Indre-et-Loire
Loir-et-Cher
Loiret
Indre
Cher
我可以使用此代码执行此操作,但它太长了:

data.LOCALISATION=data.LOCALISATION.replace('Agglomération de Tours (37))','Indre-et-Loire').replace('Nord de l’Indre et Loire (37)','Indre-et-Loire')

Python
分享到
取消 提交回答
全部回答(1)
  • 一码平川MACHEL
    2019-07-17 23:26:14

    您可以使用reregular-expression模块查找模式并使用其名称替换每个部门标识符。

    from functools import partial
    import re

    city_departments = """\

    Blois et arrondissement (41)
    Loiret Ouest (45)
    Arrond. de Chartres (28)
    Agglomération de Tours (37)
    Nord de l’Indre et Loire (37)
    Vendôme et arrondissement (41)
    Arrond. de Nogent-le-Rotrou (28)
    Loiret Est (45)
    Lochois (37)
    Romorantin et arrondissement (41)

    """

    pattern = re.compile(r'(b)(.+?)s((d+))')

    Define the department identifier -> name mapping.

    DEPT_MAP = {

    28: 'Eure-et-Loir',
    37: 'Indre-et-Loire',
    41: 'Loir-et-Cher',
    45: 'Loiret',

    }

    def replace_city_by_dept(mapping, matchobj):

    """ Replace department identifier with its name from the mapping. """
    
    key = int(matchobj.group(3))  # Dept ids are numeric.
    return mapping.get(key, matchobj.group(0))
    

    To avoid using global variables, create new partial function with the

    department mapping dictionary passed automatically.

    dept_replacer = partial(replace_city_by_dept, DEPT_MAP)

    print('Before:')
    print(city_departments)

    city_departments = pattern.sub(dept_replacer, city_departments)

    print('After:')
    print(city_departments)
    输出:

    Before:

    Blois et arrondissement (41)
    Loiret Ouest (45)
    Arrond. de Chartres (28)
    Agglomération de Tours (37)
    Nord de l?Indre et Loire (37)
    Vendôme et arrondissement (41)
    Arrond. de Nogent-le-Rotrou (28)
    Loiret Est (45)
    Lochois (37)
    Romorantin et arrondissement (41)
    

    After:

    Loir-et-Cher
    Loiret
    Eure-et-Loir
    Indre-et-Loire
    Indre-et-Loire
    Loir-et-Cher
    Eure-et-Loir
    Loiret
    Indre-et-Loire
    Loir-et-Cher
    0 0
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题
推荐课程