地名拆分,正则示例

 1 if __name__ == '__main__':
 2     def transfer(birthplace):
 3         pattern_rule = '(.*[省|自治区])(.*)'
 4         special = ['香港特别行政区', '澳门特别行政区']
 5         directly = ['北京市', '上海市', '重庆市', '天津市']
 6         if birthplace in special:
 7             return birthplace, birthplace
 8         elif birthplace in directly:
 9             return birthplace, "市辖区"
10         else:
11             group_match = re.match(pattern_rule, birthplace)
12             if group_match is not None:
13                 return group_match.group(1), group_match.group(2)
14         return None, None
15 
16 
17     a = ['山东省德州市', '内蒙古自治区兴安盟', '香港特别行政区', '北京市']
18     for i in a:
19         print(transfer(i))
原文地址:https://www.cnblogs.com/dream2sky/p/12492487.html