开发者社区> 问答> 正文

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

我有一点问题,我有几个城市的部门标识符,我想用其部门替换每个城市,最后我只有部门。我怎么能用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')

展开
收起
一码平川MACHEL 2019-01-22 11:53:17 1812 0
1 条回答
写回答
取消 提交回答
  • 您可以使用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
    2019-07-17 23:26:14
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载