Skip to content

Instantly share code, notes, and snippets.

@axaluss
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axaluss/9345239 to your computer and use it in GitHub Desktop.
Save axaluss/9345239 to your computer and use it in GitHub Desktop.
Language detection of texts using the 100 most common words of each language in an exampe using English, German and Spanish and one example text for each language.
#/usr/bin/ruby
class DetectLanguage
def calc_wc txt, lang
wc=0
txt.split(/\W+/).select{|ww|lang.include?(ww)}.map{|ww|
wc+=[(lang.size-lang.index(ww))/lang.size.to_f, 0.5].max
}
wc
end
def detect
en=%w[
the of and a to in is you that it he was for on are as with his they I at be this have from or one had by word but not what all were we when your can said there use an each which she do how their if will up other about out many then them these so some her would make like him into time has look two more write go see number no way could people my than first water been call who oil its now find long down day did get come made may part
]
de=%w[
der die und in den von zu das mit sich des auf für ist im dem nicht ein Die eine als auch es an werden aus er hat daß sie nach wird bei einer Der um am sind noch wie einem über einen Das so Sie zum war haben nur oder aber vor zur bis mehr durch man sein wurde sei In Prozent hatte kann gegen vom können schon wenn habe seine Mark ihre dann unter wir soll ich eines Es Jahr zwei Jahren diese dieser wieder keine Uhr seiner worden Und will zwischen Im immer Millionen Ein was sagte
]
es=%w[
que de no a la el es y en lo un por qué me una te los se con para mi está si bien pero yo eso las sí su tu aquí del al como le más esto ya todo esta vamos muy hay ahora algo estoy tengo nos tú nada cuando ha este sé estás así puedo cómo quiero sólo soy tiene gracias o él bueno fue ser hacer son todos
era eres vez tienes creo ella he ese voy puede sabes hola sus porque dios quién nunca dónde quieres casa favor esa dos tan señor tiempo verdad estaba mejor están va hombre usted mucho hace entonces siento tenemos puedes ahí ti vida ver alguien sr hasta sin mí solo años sobre decir uno siempre oh ir cosas también antes has ni mis día estar estamos noche nadie otra quiere parece nosotros poco padre trabajo gente mira vas sea les donde mismo hecho ellos dijo pasa dinero hijo tal otro hablar seguro claro estas lugar mundo amigo espera mierda han
]
txt1= <<EOF
Aptik es una nueva herramienta desarrollada con la idea de simplificar la RE-instalación de paquetes tras realizar una instalación limpia en una distribución Ubuntu o derivada.
EOF
txt2= <<EOF
Für so Beiträge bitte einmal #frage.
Grundsätzlich gar nicht. Müsste man ja sonst für jeden Beitrag einzeln die Sprache angeben. Du kannst die User deaspektieren oder ignorieren. Und es gibt Userscripte, die Beiträge mit von dir gewählten hashtags rausfilten können.
EOF
txt3= <<EOF
The list below of most common words in English cannot be definitive. It is based on an analysis of the Oxford English Corpus of over a billion words, and represents one study done by Oxford Online, associated with the Oxford English Dictionary.[1] This source includes writings of all sorts from "literary novels and specialist journals to everyday newspapers and magazines and from Hansard to the language of chatrooms, emails, and weblogs",[2] unlike some sources which use texts from only specific sources.[3]
EOF
langs={:de=> de, :es=> es, :en=>en}
{:es=>txt1,:de=> txt2, :en=>txt3}.map{|tl,txt|
vals=langs.to_a.map{|label,words| [label , calc_wc(txt, words)] }
vals_sorted=vals.sort_by{|label,val| val}
puts "#{vals_sorted}"
puts "text #{tl}\n\t'#{txt[0,10]}...'\n\t is #{vals_sorted.last.to_s}"
}
end
end
DetectLanguage.new.detect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment