原文译注:Davis ZHANG
2019年6月4日更新: 不幸的是,该函数不会被发布。该函数是经过认证的连接器的一部分,现在已隐藏。
在Power BI Desktop 2019年5月的更新文档,其中包括一个新的M函数:Text.ReplaceAll(截至2019年5月18日,未在微软文档中记录)。此函数简化了以前必须使用自定义函数完成的多个单词替换。
背景
使用Power Query一次替换多个文本字符串是常见的情况。几位知名博主已经编写了自己的函数来替代现有功能——比如 Chris Webb, Ivan Bondarenko 和 Imke Feldmann(Imke Feldmann的公式稍有不同——稍后将详细介绍)。
在本文,我将使用和他们一样的数据:
文本查询
文本 |
---|
the cat sat on the mat |
the cat sat next to the dog |
the dog chased the cat |
the dog sat on the mat |
let Source = #table( type table [Text = text], { {"the cat sat on the mat"}, {"the cat sat next to the dog"}, {"the dog chased the cat"}, {"the dog sat on the mat"} } ) in Source
替换查询
被替换词 | 替换为 |
---|---|
cat | bear |
mat | chair |
dog | dragon |
the | THE |
let Source = #table( type table [ Word to Replace = text, Replace With = text ], { {"cat", "bear"}, {"mat", "chair"}, {"dog", "dragon"}, {"the", "THE"} } ) in Source
函数语法
Text.ReplaceAll 接受两个参数:
- 文本
- 替换
其中第二个参数是一组对值:{“被替换词”,”替换为”}
例如以下表达式返回 “yyz”:
Text.ReplaceAll("xyz", { {"x", "y"} })
使用 Text.ReplaceAll
要在Chris的数据上使用这个函数,我们需要首先将字典转换为列表中的列表。为此,我们可以使用List.Zip。假设我们的字典表位于名为Source的步骤中,那么下面的表达式将准确地给出我们所需要的:
= List.Zip({Source[Word to Replace], Source[Replace With]})
因此完整的替换查询语句应为:
let Source = #table( type table [ Word to Replace = text, Replace With = text ], { {"cat", "bear"}, {"mat", "chair"}, {"dog", "dragon"}, {"the", "THE"} } ), ToList = List.Zip( { Source[Word to Replace], Source[Replace With] } ) in ToList
应用这个函数就很简单了。如果添加自定义列,则可以使用以下公式:
= Text.ReplaceAll([Text], Replacements)
结果如下:
注意事项
需要注意的是,该函数当前只替换子字符串,而不是整个单词。也就是说,如果在Replacements表中添加一行,如下所示:
被替换词 | 替换为 |
---|---|
cat | bear |
mat | chair |
dog | dragon |
the | THE |
air | water |
那么结果很可能不是你想要的:
如果您只需要替换整个单词,我将使用Imke的方法来解决这个问题。
请注意,该函数按顺序执行替换:如果将air-water放在列表顶部,则会得到不同的结果。
你可以下载我的.pbix文件:TextReplaceAll.pbix
(译注:此文件已被我分享至百度网盘)

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可
关于本文,如有问题或建议,欢迎您前往知乎微软BI圈发帖(备注本文链接),我将尽快回复