I’m working on a google translate package, and I’ve got the translating part, but I want a function that will do a batch translate.
function batchtranslate(inputstrings::Array{String,1}, lang_tgt="auto"::String, lang_src="auto"::String)::Array{String}
returnparts = Array(String)
for part in inputstrings
append!(returnparts, translate(part))
end
return returnparts
end
end
I do:
batchtranslate(["Hello.", "What is your name?"], "ja")
I keep getting errors no matter how I change Array{String} around. When I leave typing out of it, it seems to iterate through each character rather than each element in the input array.
I use Vector
because it’s a little clearer. The big thing appears to be returnparts
. I’m not sure what type that was getting defined as, but it wasn’t what you wanted.
function batchtranslate(inputstrings::Vector{String}, lang_tgt="auto"::String, lang_src="auto"::String)::Vector{String}
returnparts = Vector{String}()
for part in inputstrings
append!(returnparts, translate(part))
end
return returnparts
end
Assuming that lang_tgt
and lang_src
are part of the translate
api, you can use broadcasting
batchtranslate(inputstrings, lang_tgt = "auto", lang_src = "auto") = translate.(inputstrings, lang_tgt, lang_src)
As a side note, do not annotate so heavily.
1 Like
I tried your code, and it gave me:
julia> a = GoogleTrans.batchtranslate(["Hello. My name is Westly.", "What is your name?"], "ja")
ERROR: MethodError: Cannot `convert` an object of type Char to an object of type String
Closest candidates are:
convert(::Type{T}, ::T) where T<:AbstractString at strings/basic.jl:229
convert(::Type{T}, ::AbstractString) where T<:AbstractString at strings/basic.jl:230
convert(::Type{T}, ::T) where T at essentials.jl:171
Stacktrace:
[1] setindex!(::Array{String,1}, ::Char, ::Int64) at ./array.jl:847
[2] _append!(::Array{String,1}, ::Base.HasLength, ::String) at ./array.jl:989
[3] append!(::Array{String,1}, ::String) at ./array.jl:981
[4] batchtranslate(::Array{String,1}, ::String, ::String) at /home/westly/google_trans_new/googletrans.jl:38
[5] batchtranslate(::Array{String,1}, ::String) at /home/westly/google_trans_new/googletrans.jl:36
[6] top-level scope at REPL[2]:1
As for Skoffer’s code, it worked, but I’m also thinking about using multiple dispatch to add it to the translate function instead of having a separate function for batch translation.
Any ideas on how to do that?
Well, since broadcasting is a first-class citizen in Julia, the best choice is to do nothing. If the user wants to translate vector of strings, he can apply broadcast and be happy about it.
But, still, you can do something like this
translate(inputstrings::AbstractVector{S}, lang_tgt = "auto", lang_src = "auto") where {S <: AbstractString} = translate.(inputstrings, lang_tgt, lang_src)
As a side effect, this function can translate nested expressions like [["Hello", "my"], ["name is", "Alexandrou Panagouli"]]
2 Likes