Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- print "Hello"
- def foo
- puts "hi"
- end
- class Classifier
- def initialize
- @data = {}
- @totals = Hash.new(1.0)
- end
- def words(code)
- code.split(/[^a-z]/).reject{|w| w.empty?}
- end
- def train(code,lang)
- @data[lang] ||= Hash.new(1)
- for word in words(code)
- @data[lang][word] += 1
- @totals[word] += 1
- end
- end
- def prob(words,lang)
- # We really want to multiply here but I use logs
- # to avoid floating point underflow
- # (adding logs is equivalent to multiplication)
- words.inject(0.0){|c,w| c + Math.log(@data[lang][w]/@totals[w])}
- end
- def classify(code)
- ws = words(code)
- @data.keys.sort_by{|lang| prob(ws,lang)}.last
- end
- end
- # Example usage
- c = Classifier.new
- # Train from files
- c.train(open("code.rb").read, :ruby)
- c.train(open("code.py").read, :python)
- c.train(open("code.cs").read, :csharp)
- # Test it on another file
- c.classify(open("code2.py").read) # => :python (hopefully)
- int i = 5;
- int k = 0;
- for (int j = 100 ; j > i ; i++) {
- j = j + 1000 / i;
- k = k + i * j;
- }
- "package, class, implements "=> JAVA
- "<?php " => PHP
- "include main fopen strcmp stdout "=>C
- "cout"=> C++
- etc...
Add Comment
Please, Sign In to add comment