Guest User

Untitled

a guest
Jun 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. class Syllable
  2. def initialize
  3. @syllable_cache = Hash.new
  4. end
  5.  
  6. def normalize(word)
  7. return word.downcase.strip.tr('^a-z-\'','')
  8. end
  9.  
  10. def syllables(word)
  11. word = word.downcase.strip.tr('^a-z-\'','')
  12. # caching syllables reduces average run time by more than half
  13. found = @syllable_cache[word]
  14. return found unless found.nil?
  15.  
  16. subsyl = ["cial","tia","cius",
  17. "cious","giu",
  18. "ion","iou","sia$",".ely$", "ing"]
  19.  
  20. addsyl = ["ia","riet","dien","iu",
  21. "io","ii","[aeiouym]bl$",
  22. "[aeiou]{3}",
  23. "^mc","ism$",
  24. '([^aeiouy])\1l$',
  25. "[^l]lien",
  26. "^coa[dglx].",
  27. "[^gq]ua[^auieo]",
  28. "dnt$"]
  29.  
  30. # fold contraction
  31. word.tr!("'","")
  32. # chop off trailing 'e'
  33. word = word[0,word.length-1] if word[word.length-1,1] == "e"
  34.  
  35. parts = word.split /[^aeiouy]+/
  36. parts.shift if parts[0] == ""
  37. count = 0
  38. # deal with exceptions
  39. subsyl.each{ |pat|
  40. count -= 1 if word =~ /#{pat}/
  41. }
  42. addsyl.each{ |pat|
  43. count += 1 if word =~ /#{pat}/
  44. }
  45. # x
  46. count += 1 if word.length == 1 && !vowel?(word)
  47. # count vowel groups
  48. count += parts.length
  49. count = 1 if count == 0
  50.  
  51. @syllable_cache[word] = count
  52. return count
  53. end
  54.  
  55. end
  56.  
  57. s = Syllable.new
  58. puts s.syllables("Should have a count of six") # Should give us 6
  59. puts
  60. 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