Class: EnglishSpellcheck

Inherits:
Object
  • Object
show all
Defined in:
lib/english_spellchecker.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(debug: false) ⇒ EnglishSpellcheck

Returns a new instance of EnglishSpellcheck.



14
15
16
17
18
19
20
21
22
# File 'lib/english_spellchecker.rb', line 14

def initialize(debug: false)
  
  @debug = debug
  @words = Words2DotDat.words
  @spelling = ('a'..'z').map do |c|
    DidYouMean::SpellChecker.new(dictionary: @words.select {|x| x[0] == c})
  end
  
end

Class Method Details

.spell(raww, verbose: true) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/english_spellchecker.rb', line 24

def self.spell(raww, verbose: true)
  
  w = raww.downcase
  
  return raww  if @words.include? w
  list = @words.select {|x| x[0] == w[0]}
  r = DidYouMean::SpellChecker.new(dictionary: list).correct(w)
  
  if r.any? then
    
    found = r.first
    puts 'found: ' + found.inspect if verbose
    
    # return the word found along with the ending of the keyword which 
    # wasn't found.
    #
    if raww.length > found.length then
      if found == w[0..found.length-1] then
        return [found, raww[found.length..-1]]
      else
        return found
      end
    else
      if w == found[0..raww.length-1] then
        return [raww, found[raww.length..-1]]
      else
        return found
      end
    end
    
  else
    nil
  end

end

Instance Method Details

#inspectObject



60
61
62
# File 'lib/english_spellchecker.rb', line 60

def inspect()
  "#<EnglishSpellcheck:#{self.object_id} @spelling=DidYouMean::SpellChecker>"
end

#spell(raww, verbose: true) ⇒ Object Also known as: spelling



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/english_spellchecker.rb', line 64

def spell(raww, verbose: true)
  
  w = raww.downcase
  
  return raww  if @words.include? w
  c = w[0].ord - 97
  puts 'c: ' + c.inspect if @debug
  r = @spelling[c].correct w
  
  if r.any? then
    
    found = r.first
    puts 'found: ' + found.inspect if verbose

    # return the word found along with the ending of the keyword which 
    # wasn't found.
    #
    if raww.length > found.length then
      if found == w[0..found.length-1] then
        return [found, raww[found.length..-1]]
      else
        return found
      end
    else
      if w == found[0..raww.length-1] then
        return [raww, found[raww.length..-1]]
      else
        return found
      end
    end
    
  else
    nil
  end
  
end