Julia Rhymed Sentence Example


This program allows the user to compute a randomly rhymed sentence starting from an input sentence.

using HTTP
using Distributions

function loaddata!(text)
    dict = Dict{String,Array{String}}()
    @parallel  for word in split(String(text),"\n")
        try if length(word) < 3
            if !haskey(dict,word)
                dict[word] = String[]
            end
            push!(dict[word],word)
        elseif length(word) == 3
            if !haskey(dict,word[3:3])
                dict[word[3:3]] = String[]
            end
            if !haskey(dict,word)
                dict[word] = String[]
            end
            push!(dict[word[3:3]],word)
            push!(dict[word],word)
        else
            if !haskey(dict,word[length(word)-2:length(word)])
                dict[word[length(word)-2:length(word)]] = String[]
            end
            if !haskey(dict,word[length(word)-3:length(word)])
                dict[word[length(word)-3:length(word)]] = String[]
            end
            push!(dict[word[length(word)-2:length(word)]],word)
            push!(dict[word[length(word)-3:length(word)]],word)
        end catch end
    end
    return dict
end

function computerhyme!(sentece, prob, dict)
    rhymed_sentence = String[]
    for word in split(String(sentece)," ")#
        result = String[]
        try
        if length(word) == 3
            result=vcat(result,dict[word])
            result=vcat(result,dict[word[3:3]])
        elseif length(word) > 3
            result=vcat(result,dict[word[length(word)-2:length(word)]])
            result=vcat(result,dict[word[length(word)-3:length(word)]])
        end catch end

        if length(result) > 0
            if rand() > prob
                push!(rhymed_sentence,result[rand(1:length(result))])
            else
                push!(rhymed_sentence, word)
                if(prob > 0.5)
                    prob -=  0.1
                end
            end
        else
            push!(rhymed_sentence, word)
        end
    end
    return rhymed_sentence
end

words_data_big = "https://raw.githubusercontent.com/napolux/paroleitaliane/master/paroleitaliane/110000_parole_italiane_con_nomi_propri.txt"
@time res = HTTP.request("GET", words_data_big)
@time dict = loaddata!(res.body)
test_data = "Ciao elisa che fa rima con improvvisa"
prob = 0.7
@time rhymed = computerhyme!(test_data,prob,dict)
for rhyme in rhymed
    print(rhyme," ")
end
Last Update 2017.
@ Carmine Spagnuolo.