hylang 替换多个单词
hylang replace multiple words
我想在 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)
这失败了,因为 reduce
中 lambda 函数的 kv
参数被解释为单个参数(例如 ["hello" "bye"]
)而不是两个参数 "hello"
& "bye"
.
在 python 中,我可以使用 *
运算符将列表取消引用到参数,但似乎我不能在 hy 中这样做。
(defn replace [s repls]
(reduce (fn [a kv] (.replace a *kv)) repls s))
> NameError: global name '*kv' is not defined
有没有优雅的方法
- 扩展列表作为参数
- AND/OR 替换字符串中的多个单词
在 hy
?
技巧似乎是使用 (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")))
我想在 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)
这失败了,因为 reduce
中 lambda 函数的 kv
参数被解释为单个参数(例如 ["hello" "bye"]
)而不是两个参数 "hello"
& "bye"
.
在 python 中,我可以使用 *
运算符将列表取消引用到参数,但似乎我不能在 hy 中这样做。
(defn replace [s repls]
(reduce (fn [a kv] (.replace a *kv)) repls s))
> NameError: global name '*kv' is not defined
有没有优雅的方法
- 扩展列表作为参数
- AND/OR 替换字符串中的多个单词
在 hy
?
技巧似乎是使用 (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")))