Power Query中实现多值动态Text.Contains匹配的技术求助
Power Query 动态关键词匹配实现方案
需求:检查数据源每行文本是否包含搜索列表中的任意关键词,存在则返回匹配的关键词,不存在则返回null,且需适配任意长度的搜索列表(从1个到100+个词),避免拼接多个Text.Contains的冗余写法。
实现步骤与代码
- 定义搜索列表:将你的关键词转换为Power Query列表格式
- 添加自定义列,通过列表筛选逻辑实现动态匹配
以下是完整的Power Query M代码示例:
let // 替换为你的数据源(比如从Excel/CSV导入的表) Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], // 搜索列表:可直接修改这里的关键词,支持任意数量 searchList = {"Hazards", "Eliminate", "ventilation", "Avoid"}, // 添加匹配关键词列 AddMatchedWord = Table.AddColumn(Source, "匹配关键词", each let // 筛选当前行包含的所有关键词 matchedWords = List.Select(searchList, (word) => Text.Contains([Column1], word)) in // 有匹配则返回第一个关键词,无匹配返回null;若要返回所有匹配词,可改为Text.Combine(matchedWords, ", ") if List.Count(matchedWords) > 0 then matchedWords{0} else null ) in AddMatchedWord
代码说明
List.Select会遍历搜索列表中的每个词,检查当前行文本是否包含该词,自动生成匹配结果列表- 若需要忽略大小写匹配,可把
Text.Contains([Column1], word)改为Text.Contains([Column1], word, Comparer.OrdinalIgnoreCase) - 如需返回所有匹配的关键词,将
matchedWords{0}替换为Text.Combine(matchedWords, ", ")即可
测试结果(基于你提供的数据源)
| Column1 | 匹配关键词 |
|---|---|
| Physical hazards Flam. Liq. 3 - H226 Eliminate all sources of ignition. | Hazards |
| Health hazards STOT SE 3 - H336. Avoid inhalation of vapours and contact with skin and eyes. | Hazards |
| Environmental hazards Not Classified. Avoid the spillage or runoff entering drains, sewers or watercourses. | Hazards |
| Personal precautions Keep unnecessary and unprotected personnel away from the spillage. | null |
| clothing as described in Section 8 of this safety data sheet. Provide adequate ventilation. | ventilation |
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

