用列表中的特定单词替换字符串中的多个单词 [英] replace multiple words in string with specific words from list
问题描述
如何使用 M 语言将字符串中的特定词替换为表中指定的其他特定词?
How can I, using M-language, replace specific words in a string with other specific words that are specified in a table?
查看我的示例数据:
源代码:
let
someTable = Table.FromColumns({{"aa &bb &cc dd","&ee ff &gg hh &ii"}, {Table.FromColumns({{"&bb","&cc"}, {"ReplacementForbb", "ccReplacement"}},{"StringToFind", "ReplaceWith"}), Table.FromColumns({{"&ee", "&gg","&ii"}, {"OtherReplacementForee", "SomeReplacementForgg", "Replacingii"}},{"StringToFind", "ReplaceWith"})}, {"aa ReplacementForbb ccReplacement dd","OtherReplacementForee ff SomeReplacementForgg hh Replacingii"}},{"OriginalString", "Replacements", "WantedResult"})
in
someTable
推荐答案
这是一个很好的问题.您可以使用一些表格来完成此操作,并将 M 函数作为自定义列列出,如下所示:
This is a neat question. You can do this with some table and list M functions as a custom column like this:
= Text.Combine(
List.ReplaceMatchingItems(
Text.Split([OriginalString], " "),
List.Transform(Table.ToList([Replacements]),
each Text.Split(_,",")
)
),
" ")
我将使用第一行作为示例来介绍它是如何工作的.
I'll walk through how this works using the first row as an example.
[OriginalString]
是 "aa &bb &cc dd"
并且我们使用 Text.Split
将其转换为列表.
The [OriginalString]
is "aa &bb &cc dd"
and we use Text.Split
to convert it to a list.
"aa &bb &cc dd" --Text.Split--> {"aa", "&bb", "&cc", "dd"}
现在我们需要处理 [Replacements]
表并将其转换为列表列表.它开始:
Now we need to work on the [Replacements]
table and convert it into a list of lists. It starts out:
StringToFind ReplaceWith
------------------------------
&bb ReplacementForbb
&bb ccReplacement
使用 Table.ToList
这会变成一个两元素列表(因为表格有两行).
Using Table.ToList
this becomes a two element list (since the table had two rows).
{"&bb,ReplacementForbb","&cc,ccReplacement"}
在逗号上使用Text.Split
,我们可以将每个元素转化为一个列表得到
Using Text.Split
on the comma, we can transform each element into a list to get
{{"&bb","ReplacementForbb"},{"&cc","ccReplacement"}}
这是我们List.ReplaceMatchingItems
函数所需的表单.
which is the form we need for the List.ReplaceMatchingItems
function.
List.ReplaceMatchingItems(
{"aa", "&bb", "&cc", "dd"},
{{"&bb","ReplacementForbb"},{"&cc","ccReplacement"}}
)
执行替换并返回列表
{"aa","ReplacementForbb","ccReplacement","dd"}
最后,我们使用 Text.Combine
将上面的列表连接成一个字符串.
Finally, we use Text.Combine
to concatenate the list above into a single string.
"aa ReplacementForbb ccReplacement dd"
这篇关于用列表中的特定单词替换字符串中的多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!