我正在尝试编写一些代码来执行以下操作(使用类):
- 写俳句
- 计算行数,如果有 3 行则返回 true,如果没有 3 行则返回 false。
- 数数俳句中的音节。
前两个我能够实现。但是,我的音节计数器不工作,我不确定为什么……这是我的代码。
class SampleHaiku
attr_accessor :paragraph
def initialize(paragraph)
@paragraph = paragraph
end
def paragraph
@paragraph
end
def line_counter
@paragraph.lines.count
if @paragraph.lines.count == 3
puts true
else puts false
end
end
def syllable_counter
scount = []
@paragraph.split(' ').each do |letter|
if letter.to_s.downcase.include?("a")
scount << letter
elsif letter.to_s.downcase.include?("e")
elsif letter.to_s.downcase.include?("i")
scount << letter
elsif letter.to_s.downcase.include?("o")
scount << letter
elsif letter.to_s.downcase.include?("u")
scount << letter
elsif letter.to_s.downcase.include?("y")
scount << letter
else scount << " "
end
end
puts scount.to_s
return scount.join('').split(' ').size
end
end
haiku = SampleHaiku.new("green and speckled legs,
hop on logs and lily pads
splash in cool water")
puts haiku.paragraph
puts haiku.line_counter
puts haiku.syllable_counter
输出的是这个:
green and speckled legs,
hop on logs and lily pads
splash in cool water
true
["and", "hop", "on", "logs", "and", "lily", "pads", "splash", "in", "cool",
"water"]
1
---编辑---
我考虑的音节计数器包括以下内容:
计算元音。
Diagraphs(两个字母比拼一个音:“ai, ay, ee, ea, ie, ei, oo, oe, ey, ay, oy, au)算作一个元音(这是一般规则...我敢肯定会有一些异常(exception)。)
包含双元音的单词算作一个元音。在我的帖子中,我只能计算元音,根据多个来源,我知道只有大约 75% 是正确的。
显然我无法将第二个和第三个选项合并到其中,但根据我在网络上看到的不同来源,第一个选项在大约 75% 的时间内是正确的。
此外,当我将俳句文本更改为
"俳句很简单
有时他们没有意义
冰箱”
到目前为止建议的代码给出了以下...
def syllable_counter
scount = []
@paragraph.split("").each do |letter|
if letter.to_s.downcase.include?("a")
scount << letter
elsif letter.to_s.downcase.include?("e")
scount << letter
elsif letter.to_s.downcase.include?("i")
scount << letter
elsif letter.to_s.downcase.include?("o")
scount << letter
elsif letter.to_s.downcase.include?("u")
scount << letter
elsif letter.to_s.downcase.include?("y")
scount << letter
else scount << " "
end
end
scount.to_s
return scount.join('').split(' ').size
end
放
haikus are easy
sometimes they do not make sense
refrigerator
22
对比
def syllable_counter
@paragraph.scan(/[aiouy]+e*|e(?!d$|ly).|[td]|ed|le$/).size
end
放
haikus are easy
sometimes they do not make sense
refrigerator
25
最佳答案
您所做的只是检查每个带有元音的单词(出于某种原因 e 除外)并将其添加到数组中。
通过执行 @paragraph.split(' ')
,您将拆分为单词而不是字母。如果你想拆分成字母,你必须执行 @paragraph.split("")
。但即便如此,也只能计算元音的数量
可以查看第一个答案here .它有一个非常好的简单的正则表达式解决方案。
你可以这样做
@paragraph.scan(/[aiouy]+e*|e(?!d$|ly).|[td]ed|le$/).size
它并不完美,但大部分时间都有效。
如果您想要一个完美的解决方案,则需要更多的思考和英语知识。
关于 ruby 音节计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359323/