Skip to content

Instantly share code, notes, and snippets.

@maxme
Created November 1, 2013 16:31
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 maxme/7267990 to your computer and use it in GitHub Desktop.
Save maxme/7267990 to your computer and use it in GitHub Desktop.
Language detection algorithm
from collections import defaultdict
def detect_language(scores, input_str):
tokens = input_str.split()
results = defaultdict(int)
for token in tokens:
if token in scores:
language, score = scores[token][0]
results[language] += score
max_lang, max_score = max(results.items(), key=lambda x:x[1])
return max_lang
scores = {}
scores["hello"] = [ ("english", 0.01), ("french", 0)] # already sorted by score
scores["method"] = [ ("english", 0.001), ("french", 0.001)]
scores["this"] = [ ("english", 0.1), ("french", 0)]
scores["le"] = [ ("french", 0.2), ("english", 0), ]
scores["salut"] = [ ("french", 0.01), ("english", 0), ]
test = "hello this is a me"
print(test +": " + detect_language(scores, test))
test = "salut le monde"
print(test +": " + detect_language(scores, test))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment