在长生不老药中翻译字符串中的特定阶段

Translate specific phases in a string in elixir

我有一个列表,其中包含需要翻译成字符串的单词,但不需要翻译整个字符串,只需要翻译列表中的单词。

一个例子

list_with_words_that_needs_to_translate = ["here", "with one", "a string"]

需要部分翻译的字符串;

"here is a string", 

"word with one and two",

"and something that doesn't need translate"

预期结果为:

"here is a string" -> ["here", "is", "a string"] 
"word with one and two" -> ["word", "with one", "and two"]

所以我可以将片段发送到一个函数来翻译它们,returns 它们和 Enum.join 以获得新的翻译字符串。

单词将被翻译成带有 gettext 的多种语言,所以我不能使用 String.replace 并且因为列表中的单词字符串中有 spaces 我不能拆分space。

有什么建议吗?

您可以使用 reduce 对每个找到的单词应用一些函数。这是 String.upcase/1:

的示例
iex(17)> tr = fn s1 -> list_with_words |> Enum.reduce(s1, fn(x, acc) -> 
                String.replace(acc, x, String.upcase(x)) end) 
              end

iex(18)> tr.("here is a string")
"HERE is A STRING"
iex(19)> tr.("word with one and two")
"word WITH ONE and two"
iex(20)> tr.("and something that doesn't need translate")
"and something that doesn't need translate"