kenwaln-whatlanguage 1.0.4

Sign up to get free protection for your applications and to get access to all the features.
data/History.txt ADDED
@@ -0,0 +1,9 @@
1
+ == 1.0.1 / 2008-08-22
2
+
3
+ * Public release
4
+ * Removed wordlists from distribution to reduce size
5
+
6
+ == 1.0.0 / 2007-07-02
7
+
8
+ * First version with pre-built English, French, and Spanish filters
9
+
data/Manifest.txt ADDED
@@ -0,0 +1,19 @@
1
+ History.txt
2
+ Manifest.txt
3
+ README.txt
4
+ Rakefile
5
+ build_filter.rb
6
+ example.rb
7
+ lang/dutch.lang
8
+ lang/farsi.lang
9
+ lang/german.lang
10
+ lang/pinyin.lang
11
+ lang/russian.lang
12
+ lang/english.lang
13
+ lang/portuguese.lang
14
+ lang/french.lang
15
+ lang/spanish.lang
16
+ lib/bitfield.rb
17
+ lib/bloominsimple.rb
18
+ lib/whatlanguage.rb
19
+ test/test_whatlanguage.rb
data/README ADDED
File without changes
data/README.txt ADDED
@@ -0,0 +1,84 @@
1
+ whatlanguage
2
+ forked by Ken Waln from peterc-whatlanguage by Peter Cooper
3
+
4
+ == DESCRIPTION:
5
+
6
+ Text language detection. Quick, fast, memory efficient, and all in pure Ruby. Uses Bloom filters for aforementioned speed and memory benefits.
7
+
8
+ Works with Dutch, English, Farsi, French, German, Swedish, Portuguese, Russian and Spanish out of the box.
9
+
10
+ == FEATURES/PROBLEMS:
11
+
12
+ * It can be made far more efficient at the comparison stage, but all in good time..! It still beats literal dictionary approaches.
13
+ * No filter selection yet, you get 'em all loaded.
14
+ * Tests are reasonably light.
15
+ * This fork added a "large" option which uses larger fields based on language dictionary size and a
16
+ better hashing scheme to get less than 1% false positives per word. Tradeoff is speed and
17
+ memory usage.
18
+
19
+ == SYNOPSIS:
20
+
21
+ Full Example
22
+ require 'whatlanguage'
23
+
24
+ texts = []
25
+ texts << %q{Deux autres personnes ont été arrêtées durant la nuit}
26
+ texts << %q{The links between the attempted car bombings in Glasgow and London are becoming clearer}
27
+ texts << %q{En estado de máxima alertaen su nivel de crítico}
28
+ texts << %q{Returns the object in enum with the maximum value.}
29
+ texts << %q{Propose des données au sujet de la langue espagnole.}
30
+ texts << %q{La palabra "mezquita" se usa en español para referirse a todo tipo de edificios dedicados.}
31
+
32
+ texts.each { |text| puts "#{text[0..18]}... is in #{text.language.to_s.capitalize}" }
33
+
34
+ Initialize WhatLanguage with large dictionaries
35
+ wl = WhatLanguage.new(:large)
36
+
37
+ Return language with best score
38
+ wl.language(text)
39
+
40
+ Return hash with scores for all relevant languages
41
+ wl.process_text(text)
42
+
43
+ Convenience method on String
44
+ "This is a test".language # => "English"
45
+
46
+ == REQUIREMENTS:
47
+
48
+ * None, minor libraries (BloominSimple and BitField) included with this release.
49
+
50
+ == INSTALLATION:
51
+
52
+ gem sources -a http://gemcutter.org
53
+ sudo gem install kenwaln-whatlanguage
54
+
55
+ To test, go into irb, then:
56
+
57
+ require 'whatlanguage'
58
+ "Je suis un homme".language
59
+
60
+ == LICENSE:
61
+
62
+ (The MIT License)
63
+
64
+ Copyright (c) 2007-2008 Peter Cooper
65
+ Changes Copyright (c) 2009 Ken Waln
66
+
67
+ Permission is hereby granted, free of charge, to any person obtaining
68
+ a copy of this software and associated documentation files (the
69
+ 'Software'), to deal in the Software without restriction, including
70
+ without limitation the rights to use, copy, modify, merge, publish,
71
+ distribute, sublicense, and/or sell copies of the Software, and to
72
+ permit persons to whom the Software is furnished to do so, subject to
73
+ the following conditions:
74
+
75
+ The above copyright notice and this permission notice shall be
76
+ included in all copies or substantial portions of the Software.
77
+
78
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
79
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
80
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
81
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
82
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
83
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
84
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,17 @@
1
+ # -*- ruby -*-
2
+
3
+ require 'rubygems'
4
+ require 'hoe'
5
+ require './lib/whatlanguage.rb'
6
+
7
+ Hoe.new('whatlanguage', WhatLanguage::VERSION) do |p|
8
+ p.rubyforge_name = 'whatlanguage'
9
+ p.author = 'Peter Cooper'
10
+ p.email = 'whatlanguage@peterc.org'
11
+ p.summary = 'Fast, quick, textual language detection'
12
+ p.description = p.paragraphs_of('README.txt', 2..5).join("\n\n")
13
+ p.url = "http://rubyforge.org/projects/whatlanguage/"
14
+ p.changes = p.paragraphs_of('History.txt', 0..1).join("\n\n")
15
+ end
16
+
17
+ # vim: syntax=Ruby
data/build_filter.rb ADDED
@@ -0,0 +1,19 @@
1
+ # Use this to build new filters (for other languages, ideally) from /usr/share/dict/words style dictionaries..
2
+ #
3
+ # Call like so..
4
+ # ruby build_filter.rb /usr/share/dict/words lang/english.lang
5
+ # (replace params as necessary)
6
+
7
+ require 'lib/whatlanguage'
8
+ unless ARGV.length >= 2
9
+ puts <<-endUsage
10
+ usage:
11
+ ruby build_filter.rb <word list> <language file> [large]
12
+ The "large" is optional and causes larger, more accurate dictionaries
13
+ to be used
14
+ endUsage
15
+ exit
16
+ end
17
+ options = {}
18
+ options[:large] = true if ARGV[2] and ARGV[2].downcase == 'large'
19
+ WhatLanguage.filter_from_dictionary(ARGV[0],ARGV[1],options)
@@ -0,0 +1,22 @@
1
+ #! /c/ruby/bin/ruby
2
+ # Builds all of the word lists in ./wordlists/ into filter files in ./lang/
3
+
4
+ require 'lib/whatlanguage'
5
+
6
+ puts ARGV[0]
7
+ if ARGV[0] && ARGV[0].downcase == "large"
8
+ options = { :large => true }
9
+ langDir = "lang-lg"
10
+ else
11
+ options = {}
12
+ langDir = "lang"
13
+ end
14
+
15
+ languages_folder = File.join(File.dirname(__FILE__), langDir)
16
+ wordlists_folder = File.join(File.dirname(__FILE__), "wordlists")
17
+
18
+ Dir.entries(wordlists_folder).grep(/\w/).each do |lang|
19
+ next if lang == 'generators'
20
+ puts "Doing #{lang} with options #{options.inspect} "
21
+ filter = WhatLanguage.filter_from_dictionary(File.join(wordlists_folder, lang), File.join(languages_folder, lang + ".lang"),options)
22
+ end
data/example.rb ADDED
@@ -0,0 +1,51 @@
1
+ require 'lib/whatlanguage'
2
+ require 'benchmark'
3
+
4
+ texts = []
5
+
6
+ texts << %q{Deux autres personnes ont été arrêtées durant la nuit. "Induite par le quinquennat, la modernisation de nos institutions (...) est un facteur de modernité et d'efficacité", a déclaré François Fillon. "Devant cet exécutif plus resserré et plus efficace, les pouvoirs du Parlement doivent être renforcés", a-t-il ajouté, en évoquant par exemple le contrôle parlementaire des nominations à "certains postes publics."
7
+
8
+ Le premier ministre, indiquant que le président Nicolas Sarkozy entendait "réunir une commission réunissant des personnalités incontestables pour leurs compétences et représentatives de notre diversité politique qui sera chargée d'éclairer ses choix" en matière de modernisation des institutions.
9
+
10
+ "Faut-il faire élire quelques députés au scrutin proportionnel? (...) Aucun sujet ne doit être tabou", a-t-il lâché. "Enfin nous devrons engager, comme le demande le Conseil constitutionnel, une révision de la carte des circonscriptions législatives. Ce travail sera engagé dans la transparence et en y associant l'opposition".}
11
+
12
+ texts << %q{The links between the attempted car bombings in Glasgow and London are becoming clearer. Seven are believed to be doctors or medical students, while one formerly worked as a laboratory technician.
13
+
14
+ Australian media have identified a man arrested at Brisbane airport as Dr Mohammed Haneef, 27.
15
+
16
+ Two men have been arrested in Blackburn under terror laws but police have not confirmed a link with the car bombs.
17
+
18
+ The pair were detained on an industrial estate and are being held at a police station in Lancashire on suspicion of offences under the Terrorism Act 2000.
19
+
20
+ Thousands of passengers travelling from Heathrow Airport's Terminal 4 face major delays after a suspect bag sparked a security alert.
21
+
22
+ BAA said the departure lounge was partially evacuated and departing passengers were being re-screened, causing some cancellations and delays.}
23
+
24
+ texts << %q{En estado de máxima alertaen su nivel de crítico. Cinco detenciones hasta el momento parecen indicar que los coches bomba de Londres y Glasgow fueron obra de una misma célula de terroristas islámicos con residencia en el Reino Unido, posiblemente con alguna conexión con otros grupos previamente desarticulados. La relación con éstos, singularmente con el núcleo de Dhiren Barot (condenado a 30 años por sus planes de llenar limusinas con bombonas de gas para provocar una masiva explosión), podría haber llevado a su detención tiempo atrás y su puesta en libertad al no existir suficientes pruebas contra ellos.}
25
+
26
+ texts << %q{Fern- und Regionalzüge, aber auch die S-Bahnen in den Großstädten stehen still. Gerade hat die Kanzlerin die Ergebnisse des Energiegipfels mit der Wirtschaft, den Energieerzeugern und Verbraucherschützern referiert, die "sachliche Atmosphäre" gelobt. Da wird der Umweltminister von einem Journalisten an seinen Ausspruch vom "Wirtschaftsstalinisten" erinnert, mit dem er jüngst den BASF-Vorstandschef Jürgen Hambrecht belegt hat im Streit um die ehrgeizigen Ziele der deutschen Klimapolitik. Wie haben denn seine Beiträge in der Runde für eine sachliche Atmosphäre ausgesehen? Gabriel überlegt, aber die Kanzlerin ist schneller.}
27
+
28
+ #texts << %q{Deux autres personnes ont été arrêtées durant la nuit}
29
+ #texts << %q{The links between the attempted car bombings in Glasgow and London are becoming clearer}
30
+ #texts << %q{En estado de máxima alertaen su nivel de crítico}
31
+ #texts << %q{Returns the object in enum with the maximum value.}
32
+ #texts << %q{Propose des données au sujet de la langue espagnole.}
33
+ #texts << %q{La palabra "mezquita" se usa en español para referirse a todo tipo de edificios dedicados.}
34
+ #texts << %q{Fern- und Regionalzüge, aber auch die S-Bahnen in den Großstädten stehen still.}
35
+
36
+ #texts.collect! { |t| (t + " ") * 5 }
37
+
38
+ @wl = WhatLanguage.new(:all)
39
+
40
+ puts Benchmark.measure {
41
+
42
+ 100.times do
43
+ texts.each { |text|
44
+ lang = text.language.to_s.capitalize
45
+ # puts "#{text[0..18]}... is in #{lang}"
46
+ # puts @wl.process_text(text).sort_by{|a,b| b }.reverse.inspect
47
+ # puts "---"
48
+ }
49
+ end
50
+
51
+ }
data/lang/dutch.lang ADDED
Binary file
data/lang/english.lang ADDED
Binary file
data/lang/farsi.lang ADDED
Binary file
data/lang/french.lang ADDED
Binary file
data/lang/german.lang ADDED
Binary file
data/lang/pinyin.lang ADDED
Binary file
Binary file
data/lang/russian.lang ADDED
Binary file
data/lang/spanish.lang ADDED
Binary file
data/lang/swedish.lang ADDED
Binary file
data/lib/bitfield.rb ADDED
@@ -0,0 +1,64 @@
1
+ # NAME: BitField
2
+ # AUTHOR: Peter Cooper
3
+ # LICENSE: MIT ( http://www.opensource.org/licenses/mit-license.php )
4
+ # COPYRIGHT: (c) 2007 Peter Cooper (http://www.petercooper.co.uk/)
5
+ # VERSION: v4
6
+ # HISTORY: v4 (better support for loading and dumping fields)
7
+ # v3 (supports dynamic bitwidths for array elements.. now doing 32 bit widths default)
8
+ # v2 (now uses 1 << y, rather than 2 ** y .. it's 21.8 times faster!)
9
+ # v1 (first release)
10
+ #
11
+ # DESCRIPTION: Basic, pure Ruby bit field. Pretty fast (for what it is) and memory efficient.
12
+ # I've written a pretty intensive test suite for it and it passes great.
13
+ # Works well for Bloom filters (the reason I wrote it).
14
+ #
15
+ # Create a bit field 1000 bits wide
16
+ # bf = BitField.new(1000)
17
+ #
18
+ # Setting and reading bits
19
+ # bf[100] = 1
20
+ # bf[100] .. => 1
21
+ # bf[100] = 0
22
+ #
23
+ # More
24
+ # bf.to_s = "10101000101010101" (example)
25
+ # bf.total_set .. => 10 (example - 10 bits are set to "1")
26
+
27
+ class BitField
28
+ attr_reader :size
29
+ attr_accessor :field
30
+ include Enumerable
31
+
32
+ ELEMENT_WIDTH = 32
33
+
34
+ def initialize(size)
35
+ @size = size
36
+ @field = Array.new(((size - 1) / ELEMENT_WIDTH) + 1, 0)
37
+ end
38
+
39
+ # Set a bit (1/0)
40
+ def []=(position, value)
41
+ value == 1 ? @field[position / ELEMENT_WIDTH] |= 1 << (position % ELEMENT_WIDTH) : @field[position / ELEMENT_WIDTH] ^= 1 << (position % ELEMENT_WIDTH)
42
+ end
43
+
44
+ # Read a bit (1/0)
45
+ def [](position)
46
+ @field[position / ELEMENT_WIDTH] & 1 << (position % ELEMENT_WIDTH) > 0 ? 1 : 0
47
+ end
48
+
49
+ # Iterate over each bit
50
+ def each(&block)
51
+ @size.times { |position| yield self[position] }
52
+ end
53
+
54
+ # Returns the field as a string like "0101010100111100," etc.
55
+ def to_s
56
+ inject("") { |a, b| a + b.to_s }
57
+ end
58
+
59
+ # Returns the total number of bits that are set
60
+ # (The technique used here is about 6 times faster than using each or inject direct on the bitfield)
61
+ def total_set
62
+ @field.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
63
+ end
64
+ end
@@ -0,0 +1,88 @@
1
+ # NAME: BloominSimple
2
+ # AUTHOR: Peter Cooper
3
+ # LICENSE: MIT ( http://www.opensource.org/licenses/mit-license.php )
4
+ # COPYRIGHT: (c) 2007 Peter Cooper
5
+ # DESCRIPTION: Very basic, pure Ruby Bloom filter. Uses my BitField, pure Ruby
6
+ # bit field library (http://snippets.dzone.com/posts/show/4234).
7
+ # Supports custom hashing (default is 3).
8
+ #
9
+ # Create a Bloom filter that uses default hashing with 1Mbit wide bitfield
10
+ # bf = BloominSimple.new(1_000_000)
11
+ #
12
+ # Add items to it
13
+ # File.open('/usr/share/dict/words').each { |a| bf.add(a) }
14
+ #
15
+ # Check for existence of items in the filter
16
+ # bf.includes?("people") # => true
17
+ # bf.includes?("kwyjibo") # => false
18
+ #
19
+ # Add better hashing (c'est easy!)
20
+ # require 'digest/sha1'
21
+ # b = BloominSimple.new(1_000_000) do |item|
22
+ # Digest::SHA1.digest(item.downcase.strip).unpack("VVVV")
23
+ # end
24
+ #
25
+ # More
26
+ # %w{wonderful ball stereo jester flag shshshshsh nooooooo newyorkcity}.each do |a|
27
+ # puts "#{sprintf("%15s", a)}: #{b.includes?(a)}"
28
+ # end
29
+ #
30
+ # # => wonderful: true
31
+ # # => ball: true
32
+ # # => stereo: true
33
+ # # => jester: true
34
+ # # => flag: true
35
+ # # => shshshshsh: false
36
+ # # => nooooooo: false
37
+ # # => newyorkcity: false
38
+
39
+ require File.join(File.dirname(__FILE__), 'bitfield')
40
+
41
+ class BloominSimple
42
+ attr_accessor :bitfield, :hasher
43
+
44
+ def initialize(bitsize, &block)
45
+ @bitfield = BitField.new(bitsize)
46
+ @size = bitsize
47
+ @hasher = block || lambda do |word|
48
+ word = word.downcase.strip
49
+ [h1 = word.sum, h2 = word.hash, h2 + h1 ** 3]
50
+ end
51
+ end
52
+
53
+ # Add item to the filter
54
+ def add(item)
55
+ @hasher[item].each { |hi| @bitfield[hi % @size] = 1 }
56
+ end
57
+
58
+ # Find out if the filter possibly contains the supplied item
59
+ def includes?(item)
60
+ @hasher[item].each { |hi| return false unless @bitfield[hi % @size] == 1 } and true
61
+ end
62
+
63
+ # Allows comparison between two filters. Returns number of same bits.
64
+ def &(other)
65
+ raise "Wrong sizes" if self.bitfield.size != other.bitfield.size
66
+ same = 0
67
+ #self.bitfield.size.times do |pos|
68
+ # same += 1 if self.bitfield[pos] & other.bitfield[pos] == 1
69
+ #end
70
+ self.bitfield.total_set.to_s + "--" + other.bitfield.total_set.to_s
71
+ end
72
+
73
+ # Dumps the bitfield for a bloom filter for storage
74
+ def dump
75
+ [@size, *@bitfield.field].pack("I*")
76
+ #Marshal.dump([@size, @bitfield])
77
+ end
78
+
79
+ # Creates a new bloom filter object from a stored dump (hasher has to be resent though for additions)
80
+ def self.from_dump(data, &block)
81
+ data = data.unpack("I*")
82
+ #data = Marshal.load(data)
83
+ temp = new(data[0], &block)
84
+ temp.bitfield.field = data[1..-1]
85
+ temp
86
+ end
87
+ end
88
+
@@ -0,0 +1,94 @@
1
+ require File.join(File.dirname(__FILE__), 'bloominsimple')
2
+ require 'digest/sha1'
3
+
4
+ class WhatLanguage
5
+ VERSION = '1.0.3'
6
+
7
+ HASHERS = [
8
+ lambda { |item| Digest::SHA1.digest(item.downcase.strip).unpack("VV") } ,
9
+ lambda { |item| Digest::SHA2.digest(item.downcase.strip).unpack("xxxxVVVVVVV") }
10
+ ]
11
+
12
+ BITFIELD_WIDTH = 2_000_000
13
+
14
+ @@data = {}
15
+
16
+ def initialize(options = {})
17
+ lang = hashType= nil
18
+ if options == :large || (options.kind_of?(Hash) && options[:large])
19
+ lang = "lang-lg"
20
+ else
21
+ lang = "lang"
22
+ end
23
+ languages_folder = File.join(File.dirname(__FILE__), "..", lang)
24
+ Dir.entries(languages_folder).grep(/\.lang/).each do |lang|
25
+ if !@@data[lang[/\w+/].to_sym]
26
+ lfile = File.new(File.join(languages_folder, lang), 'rb')
27
+ hashType = lfile.read(4).unpack("I")[0]
28
+ @@data[lang[/\w+/].to_sym] = BloominSimple.from_dump(lfile.read, &HASHERS[hashType])
29
+ end
30
+ end
31
+ end
32
+
33
+ def reinit(options = {})
34
+ @@data = nil
35
+ initialize(options = {})
36
+ end
37
+
38
+ # Very inefficient method for now.. but still beats the non-Bloom alternatives.
39
+ # Change to better bit comparison technique later..
40
+ def process_text(text)
41
+ results = Hash.new(0)
42
+ it = 0
43
+ text.split.collect {|a| a.downcase }.each do |word|
44
+ it += 1
45
+ @@data.keys.each do |lang|
46
+ results[lang] += 1 if @@data[lang].includes?(word)
47
+ end
48
+
49
+ # Every now and then check to see if we have a really convincing result.. if so, exit early.
50
+ if it % 4 == 0 && results.size > 1
51
+ top_results = results.sort_by{|a,b| b}.reverse[0..1]
52
+
53
+ # Next line may need some tweaking one day..
54
+ break if top_results[0][1] > 4 && ((top_results[0][1] > top_results[1][1] * 2) || (top_results[0][1] - top_results[1][1] > 25))
55
+ end
56
+
57
+ #break if it > 100
58
+ end
59
+ results
60
+ end
61
+
62
+ def language(text)
63
+ process_text(text).max { |a,b| a[1] <=> b[1] }.first rescue nil
64
+ end
65
+
66
+ def self.filter_from_dictionary(filename, outfilename, options = {})
67
+ size = 0
68
+ hasher = nil
69
+ infile = File.open(filename)
70
+ if options == :large || options[:large]
71
+ lines = 0
72
+ infile.each {|word| lines += 1}
73
+ size = 10*lines
74
+ hasherId = 1
75
+ else
76
+ size = BITFIELD_WIDTH
77
+ hasherId = 0
78
+ end
79
+ bf = BloominSimple.new(size, &HASHERS[hasherId])
80
+ infile.rewind
81
+ infile.each { |word| bf.add(word) }
82
+ outfile = File.open(outfilename,"wb")
83
+ outfile.write([hasherId].pack("I"))
84
+ outfile.write(bf.dump)
85
+ outfile.close
86
+ end
87
+
88
+ end
89
+
90
+ class String
91
+ def language
92
+ WhatLanguage.new(:all).language(self)
93
+ end
94
+ end
@@ -0,0 +1,42 @@
1
+ # -*- coding: utf-8 -*-
2
+ require "test/unit"
3
+
4
+ require File.join(File.dirname(__FILE__), "..", "lib", "whatlanguage")
5
+
6
+ class TestWhatLanguage < Test::Unit::TestCase
7
+ def setup
8
+ @wl = WhatLanguage.new(:all)
9
+ end
10
+
11
+ def test_string_method
12
+ assert_equal :english, "This is a test".language
13
+ end
14
+
15
+ def test_french
16
+ assert_equal :french, @wl.language("Bonjour, je m'appelle Sandrine. Voila ma chatte.")
17
+ end
18
+
19
+ def test_spanish
20
+ assert_equal :spanish, @wl.language("La palabra mezquita se usa en español para referirse a todo tipo de edificios dedicados.")
21
+ end
22
+
23
+ def test_swedish
24
+ assert_equal :swedish, @wl.language("Den spanska räven rev en annan räv alldeles lagom.")
25
+ end
26
+
27
+ def test_russian
28
+ assert_equal :russian, @wl.language("Все новости в хронологическом порядке")
29
+ end
30
+
31
+ def test_nothing
32
+ assert_nil @wl.language("")
33
+ end
34
+
35
+ def test_something
36
+ assert_not_nil @wl.language("test")
37
+ end
38
+
39
+ def test_processor
40
+ assert_kind_of Hash, @wl.process_text("this is a test")
41
+ end
42
+ end
@@ -0,0 +1,42 @@
1
+ # -*- coding: utf-8 -*-
2
+ require "test/unit"
3
+
4
+ require File.join(File.dirname(__FILE__), "..", "lib", "whatlanguage")
5
+
6
+ class TestWhatLanguage < Test::Unit::TestCase
7
+ def setup
8
+ @wl = WhatLanguage.new(:large)
9
+ end
10
+
11
+ def test_string_method
12
+ assert_equal :english, "This is a test".language
13
+ end
14
+
15
+ def test_french
16
+ assert_equal :french, @wl.language("Bonjour, je m'appelle Sandrine. Voila ma chatte.")
17
+ end
18
+
19
+ def test_spanish
20
+ assert_equal :spanish, @wl.language("La palabra mezquita se usa en español para referirse a todo tipo de edificios dedicados.")
21
+ end
22
+
23
+ def test_swedish
24
+ assert_equal :swedish, @wl.language("Den spanska räven rev en annan räv alldeles lagom.")
25
+ end
26
+
27
+ def test_russian
28
+ assert_equal :russian, @wl.language("Все новости в хронологическом порядке")
29
+ end
30
+
31
+ def test_nothing
32
+ assert_nil @wl.language("")
33
+ end
34
+
35
+ def test_something
36
+ assert_not_nil @wl.language("test")
37
+ end
38
+
39
+ def test_processor
40
+ assert_kind_of Hash, @wl.process_text("this is a test")
41
+ end
42
+ end
@@ -0,0 +1,40 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = "kenwaln-whatlanguage"
3
+ s.version = "1.0.4"
4
+ s.date = "2009-11-02"
5
+ s.summary = "Natural language detection for text samples"
6
+ s.email = "kenwaln@pacbell.net"
7
+ s.homepage = "http://github.com/kenwaln/whatlanguage"
8
+ s.description = "WhatLanguage rapidly detects the language of a sample of text"
9
+ s.has_rdoc = true
10
+ s.authors = ["Peter Cooper", "Ken Waln"]
11
+ s.files = [
12
+ "build_filter.rb",
13
+ "build_lang_from_wordlists.rb",
14
+ "example.rb",
15
+ "History.txt",
16
+ "lang/dutch.lang",
17
+ "lang/english.lang",
18
+ "lang/farsi.lang",
19
+ "lang/french.lang",
20
+ "lang/german.lang",
21
+ "lang/pinyin.lang",
22
+ "lang/portuguese.lang",
23
+ "lang/russian.lang",
24
+ "lang/spanish.lang",
25
+ "lang/swedish.lang",
26
+ "lib/bitfield.rb",
27
+ "lib/bloominsimple.rb",
28
+ "lib/whatlanguage.rb",
29
+ "Manifest.txt",
30
+ "Rakefile",
31
+ "README",
32
+ "README.txt",
33
+ "test/test_whatlanguage.rb",
34
+ "test/test_whatlanguage_lg.rb",
35
+ "whatlanguage.gemspec"]
36
+
37
+ s.rdoc_options = ["--main", "README.txt"]
38
+ s.extra_rdoc_files = ["History.txt", "Manifest.txt", "README.txt"]
39
+ end
40
+
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kenwaln-whatlanguage
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.4
5
+ platform: ruby
6
+ authors:
7
+ - Peter Cooper
8
+ - Ken Waln
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+
13
+ date: 2009-11-02 00:00:00 -08:00
14
+ default_executable:
15
+ dependencies: []
16
+
17
+ description: WhatLanguage rapidly detects the language of a sample of text
18
+ email: kenwaln@pacbell.net
19
+ executables: []
20
+
21
+ extensions: []
22
+
23
+ extra_rdoc_files:
24
+ - History.txt
25
+ - Manifest.txt
26
+ - README.txt
27
+ files:
28
+ - build_filter.rb
29
+ - build_lang_from_wordlists.rb
30
+ - example.rb
31
+ - History.txt
32
+ - lang/dutch.lang
33
+ - lang/english.lang
34
+ - lang/farsi.lang
35
+ - lang/french.lang
36
+ - lang/german.lang
37
+ - lang/pinyin.lang
38
+ - lang/portuguese.lang
39
+ - lang/russian.lang
40
+ - lang/spanish.lang
41
+ - lang/swedish.lang
42
+ - lib/bitfield.rb
43
+ - lib/bloominsimple.rb
44
+ - lib/whatlanguage.rb
45
+ - Manifest.txt
46
+ - Rakefile
47
+ - README
48
+ - README.txt
49
+ - test/test_whatlanguage.rb
50
+ - test/test_whatlanguage_lg.rb
51
+ - whatlanguage.gemspec
52
+ has_rdoc: true
53
+ homepage: http://github.com/kenwaln/whatlanguage
54
+ licenses: []
55
+
56
+ post_install_message:
57
+ rdoc_options:
58
+ - --main
59
+ - README.txt
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: "0"
67
+ version:
68
+ required_rubygems_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: "0"
73
+ version:
74
+ requirements: []
75
+
76
+ rubyforge_project:
77
+ rubygems_version: 1.3.5
78
+ signing_key:
79
+ specification_version: 3
80
+ summary: Natural language detection for text samples
81
+ test_files: []
82
+