清理嵌套的 re.sub 语句
有人能帮我整理一下这个在Python中使用的嵌套正则表达式(re.sub)吗?我知道一定有更好的方法,但我就是想不出来。
re.sub('.*Chairman.*','Executive Director',re.sub('.*Managing Director.*','Executive Director',row['capacity']))
我有一列字符串(row['capacity']),是从数据库中提取出来的一部分数据。我想遍历这列数据,把里面包含“chairman”或“managing director”的行替换成“Executive director”,然后再写入数据集中。
这是完整的代码行:
wrhkset = set (( row['organization'], row['lastname'], row['givenname'], re.sub('.*Chairman.*','Executive Director',re.sub('.*Managing Director.*','Executive Director',row['capacity'])) ) for row in wrhk)
注意:'wrhk'是一个包含列表的元组。如果需要的话,我可以提供更多代码,但我主要是希望能找到一种更简洁的方法来处理我现在的嵌套re.sub
语句。
提前谢谢大家!
2 个回答
-1
在@ubuntu的回答基础上,我使用了一个“或”运算符和re.compile:
patterns = re.compile('(.*Chairman.*)|(.*Managing Director.*)|(.*Chief Executive.*)|(.*CEO.*)')
然后:
wrhkset = set (( row['organization'], row['lastname'], row['givenname'], patterns.sub('Executive Director',row['capacity']) ) for row in wrhk)
这样我就可以不断添加模式,而不会让我的代码变得难以阅读。
谢谢!
2
你可以用一个 |
来把两个正则表达式用“或”连接起来:
re.sub(r'''(?x)
.*(
Chairman | Managing[]Director # or
).*
''','Executive Director', row['capacity'])