0

我想在hylang中对字符串执行多个替换操作

鉴于hy与python非常相似,我在 Python 上找到了一个相关的解决方案replace multiple strings

# python
def replace(s, repls):
   reduce(lambda a, kv: a.replace(*kv), repls, s)
replace("hello, world", [["hello", "goodbye"],["world", "earth"]])
> 'goodbye, earth'

所以我试图将它移植到hy

;hy
(defn replace [s repls]
    (reduce (fn [a kv] (.replace a kv)) repls s))
(replace "hello, world", [["hello" "bye"] ["earth" "moon"]])
> TypeError: replace() takes at least 2 arguments (1 given)

这失败了,因为kvlambda 函数 in 的参数reduce被解释为单个 arg(例如["hello" "bye"])而不是两个 args "hello"& "bye"

在 python 中,我可以使用*-operator 将列表取消引用到参数,但似乎我不能在 hy.

(defn replace [s repls]
    (reduce (fn [a kv] (.replace a *kv)) repls s))
> NameError: global name '*kv' is not defined

有没有优雅的方法

  • 展开列表作为参数
  • AND/OR替换字符串中的多个单词

hy

4

1 回答 1

1

诀窍似乎是使用(apply)

(defn replace-words
      [s repls]
      (reduce (fn [a kv] (apply a.replace kv)) repls s))
(replace-words "hello, world" (, (, "hello" "goodbye") (, "world" "blue sky")))
于 2015-10-08T18:19:13.133 回答