【问题标题】:Translate specific phases in a string in elixir在长生不老药中翻译字符串中的特定阶段
【发布时间】:2018-03-22 18:16:00
【问题描述】:

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

一个例子

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"]

所以我可以将片段发送到翻译它们的函数,返回它们和 Enum.join 以获取新的翻译字符串。

这些单词将使用 gettext 翻译成多种语言,所以我不能使用String.replace,而且由于列表中的单词字符串中有空格,我不能在空格上分割。

有什么建议吗?

【问题讨论】:

  • "word with one and two" -> ["word", "with one", "and two"] -> 确定?名单上没有“和二”。不应该是["word", "with one", "and", "two"]
  • @Grych,确定与否,没关系,我只是在列表中的单词之后,其他的如何拆分可以反正只要他们在那里,所以我可以翻译列表中的单词后将字符串重新连接在一起。
  • 你不能把它们扔进地图函数吗? list_with_words_that_needs_to_translate |> Enum.map(&(gettext(&1))) |> Enum.join
  • 你有没有想过每个语言的片段顺序是否相同?我最近遇到了这个问题,并通过两个级别的 gettext 翻译解决了它,即首先获取片段here = gettext("here"); a_string = gettext("a string"),然后将它们插入到最终字符串中:gettext("%{here} is %{a_string}", here: here, a_string: a_string)。这样,您可以根据需要覆盖特定语言的最终模板。

标签: string elixir gettext


【解决方案1】:

您可以使用 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"

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多