Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Syllable
- def initialize
- @syllable_cache = Hash.new
- end
- def normalize(word)
- return word.downcase.strip.tr('^a-z-\'','')
- end
- def syllables(word)
- word = word.downcase.strip.tr('^a-z-\'','')
- # caching syllables reduces average run time by more than half
- found = @syllable_cache[word]
- return found unless found.nil?
- subsyl = ["cial","tia","cius",
- "cious","giu",
- "ion","iou","sia$",".ely$", "ing"]
- addsyl = ["ia","riet","dien","iu",
- "io","ii","[aeiouym]bl$",
- "[aeiou]{3}",
- "^mc","ism$",
- '([^aeiouy])\1l$',
- "[^l]lien",
- "^coa[dglx].",
- "[^gq]ua[^auieo]",
- "dnt$"]
- # fold contraction
- word.tr!("'","")
- # chop off trailing 'e'
- word = word[0,word.length-1] if word[word.length-1,1] == "e"
- parts = word.split /[^aeiouy]+/
- parts.shift if parts[0] == ""
- count = 0
- # deal with exceptions
- subsyl.each{ |pat|
- count -= 1 if word =~ /#{pat}/
- }
- addsyl.each{ |pat|
- count += 1 if word =~ /#{pat}/
- }
- # x
- count += 1 if word.length == 1 && !vowel?(word)
- # count vowel groups
- count += parts.length
- count = 1 if count == 0
- @syllable_cache[word] = count
- return count
- end
- end
- s = Syllable.new
- puts s.syllables("Should have a count of six") # Should give us 6
- puts
- puts s.syllables("Perhaps a more challenging test. The count should be fourteen") # Should give us 14
Add Comment
Please, Sign In to add comment