案例:要把某个字符串依据分隔符拆分不同的字段,该字符串包含多种不同的分隔符,如s='ab:cd|efg|hi,jkl|mn\topq:rst,uvw\txyz'。
其中<,>、<:>、<|>、<\t>是分隔符,如何处理?
方法1:连续使用str.split()方法,每次处理一种分隔符号
def my_split(s, seps):
res = [s]
for sep in seps:
t = []
list(map(lambda ss : t.extend(ss.split(sep)), res))
res = t
return res
s = 'ab:cd|efg|hi,jkl|mn\topq:rst,uvw\txyz'
my_split(s, ',:|\t')
#或者用reduce函数
my_split2 = lambda s, seps: reduce(lambda l, sep: sum(map(lambda ss: ss.split(sep), l), []), seps, [s])
my_split2(s, ',:|\t')
方法2: 使用正则表达式的re.split()方法
import re
s = 'ab:cd|efg|hi,jkl|mn\topq:rst,uvw\txyz'
re.split('[,:|\t]+', s)
相关知识点:
https://www.cnblogs.com/lonkiss/p/understanding-python-reduce-function.html
弄明白python reduce 函数
map()函数
https://www.runoob.com/python/python-func-map.html