Power Query自定义函数:从逗号分隔字符串提取指定分段
Power Query自定义函数优化:按地址分段提取指定内容
问题场景
现有地址列格式如下,部分地址包含5个分段,部分包含4个分段:
- De Villiers Street, Wellington North, Wellington, Western Cape, South Africa
- Main Street, Paarl, Western Cape, South Africa
需要创建自定义函数,能根据地址的分段数提取指定分段。原函数代码如下:
(Location,SectionNr) => let Sections = Text.Split(Location,","), Section = Sections[SectionNr] in Section
原代码存在两个核心问题:
- 索引起始值错误:Power Query的列表索引从0开始,而非1。比如第一个地址拆分后是5个元素(索引0-4),你期望提取的
Western Cape是索引3,而非4;第二个地址拆分后是4个元素(索引0-3),目标内容是索引2,而非3。 - 提取同层级内容需手动适配参数:如果要提取省份这类固定层级的内容,每次都要根据分段数传不同的
SectionNr,效率很低。
优化方案
方案1:适配1-based索引的通用提取函数
把用户传入的SectionNr转换成0-based索引,同时处理地址前后可能存在的空格(拆分后每个分段可能带前导空格):
GetSection = (Location as text, SectionNr as number) => let // 拆分地址并去除每个分段的前后空格 Sections = List.Transform(Text.Split(Location, ","), Text.Trim), // 转换为0-based索引,同时判断索引是否合法 ValidatedIndex = if SectionNr >=1 and SectionNr <= List.Count(Sections) then SectionNr - 1 else null, Section = if ValidatedIndex <> null then Sections{ValidatedIndex} else "无效的分段编号" in Section
使用示例:
// 提取5段地址中的第4个分段(Western Cape) GetSection("De Villiers Street, Wellington North, Wellington, Western Cape, South Africa", 4) // 提取4段地址中的第3个分段(Western Cape) GetSection("Main Street, Paarl, Western Cape, South Africa", 3)
方案2:自动提取固定层级内容(如省份)
如果目标是提取省份(始终是倒数第二个分段),可以直接根据列表长度取对应位置,无需传入分段编号:
GetProvince = (Location as text) => let Sections = List.Transform(Text.Split(Location, ","), Text.Trim), // 省份是倒数第二个分段,索引为列表长度-2 Province = if List.Count(Sections) >=2 then Sections{List.Count(Sections)-2} else "地址格式错误" in Province
使用示例:
GetProvince("De Villiers Street, Wellington North, Wellington, Western Cape, South Africa") GetProvince("Main Street, Paarl, Western Cape, South Africa")
上述两个调用都会返回Western Cape。
内容的提问来源于stack exchange,提问作者LordRofticus
相关产品推荐
相关产品推荐

