感谢 @xgdgsc @AndyJado 的回复。
考虑到其他用户可能有相同需求,即把Dict传入replace函数,在此,我当个搬运工,综合两位提供的方法和链接,小结如下。(测试版本:Julia 1.7.2)
想实现的效果
事先把替换前后的键值对定义到字典中,是方便的。大家应该不会否认吧?
举个例子,希望通过以下语句:
strs = "Li Lei uses Python.";
dct = Dict("Li Lei"=>"Han Meimei", "Python"=>"Julia");
replace(strs, dct)
得到如下输出:
"Han Meimei uses Julia."
报错
实际运行时,报错了。
MethodError: no method matching replace(::String, ::Dict{String, String})
Closest candidates are:
replace(::Union{Function, Type}, ::Any; count) at /usr/share/julia/base/set.jl:622
replace(::String, ::Pair...; count) where N at /usr/share/julia/base/strings/util.jl:535
replace(::AbstractString, ::Pair...; count) at /usr/share/julia/base/strings/util.jl:634
...
Stacktrace:
[1] top-level scope
@ In[16]:3
[2] eval
@ ./boot.jl:373 [inlined]
[3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base ./loading.jl:1196
解决办法探讨
方法1:…召唤魔法(所知有限,随便这么叫一下,我一时不知怎么对其称呼)
是 @xgdgsc 道出了这个技能。
strs = "Li Lei uses Python.";
dct = Dict("Li Lei"=>"Han Meimei", "Python"=>"Julia");
replace(strs, dct) # 错误
replace(strs, dct...) # 正确
方法2: 通过构造函数,来实现映射。这是 @xgdgsc 链接中提及的方法。
strs = "Li Lei uses Python.";
reg = r"Li Lei|Python";
dct = Dict("Li Lei"=>"Han Meimei", "Python"=>"Julia");
replace(strs, reg=>(x->dct[x])) # 不熟悉的小伙伴,注意下:x->dct[x]构造了一个函数,它的输入值为x,输出值为dct[x]。
输出
"Han Meimei uses Julia."
从链接中的表述来看,这种方法的运算效率不错。
办法3: 更进一步地,利用多重派发机制,用户自行为replace函数增加能处理(::String, ::Dict{String, String})的新方法。比如,把方法1或者用户自行构思的其它方法增加到replace函数中。
原生replace函数接受一系列Pair或一个Dict{Char, Char}
Pair时: 来自官方的例子
replace([1, missing], missing=>0)
输出
2-element Vector{Int64}:
1
0
Dict{Char, Char}时: 来自 @AndyJado 的例子
let
astring = "i am not any expert, neither an experienced one, but I'd like to cou re nao"
uncode = "abcde"
decode = "12345"
book = Dict(i=>j for (i,j) in zip(uncode,decode))
replace(astring,book...)
end
输出
Dict{Char, Char} with 5 entries:
'a' => '1'
'c' => '3'
'd' => '4'
'e' => '5'
'b' => '2'