我回答了自己的问题。忘了初始化count = 0
段落中有一堆句子。
a = "Hello there. this is the best class. but does not offer anything."
为例。 .split
字符串,以便a_sentence = a.split(".")
"hello world".capitalize!
如果它是nil
对我来说意味着它已经被大写了
编辑.capitalize!
.strip.capitalize!.nil?
但我似乎无法输出有多少资本化。
修改
a_sentence.each do |sentence|
if (sentence.strip.capitalize!.nil?)
count += 1
puts "#{count} capitalized"
end
end
输出:
1 capitalized
感谢您的帮助。我会坚持使用上面的代码,我可以在Ruby中知道的框架内理解。 :)
答案 0 :(得分:1)
试试这个:
b = []
a.split(".").each do |sentence|
b << sentence.strip.capitalize
end
b = b.join(". ") + "."
# => "Hello there. This is the best class. But does not offer anything."
答案 1 :(得分:1)
您帖子的标题会产生误导,因为从您的代码中,您似乎想要在句子的开头获取大写字母的数量。
假设每个句子都在一段时间(一个完整的句号)后面跟一个空格完成,以下内容对您有用:
split_str = ". "
regex = /^[A-Z]/
paragraph_text.split(split_str).count do |sentence|
regex.match(sentence)
end
如果您只想确保每个首字母大写,您可以尝试以下方法:
paragraph_text.split(split_str).map(&:capitalize).join(split_str) + split_str
答案 2 :(得分:1)
没有必要将字符串拆分成句子:
str = "It was the best of times. sound familiar? Out, damn spot! oh, my."
str.scan(/(?:^|[.!?]\s)\s*\K[A-Z]/).length
#=> 2
在结束x
之后添加/
,可以使用文档编写正则表达式:
r = /
(?: # start a non-capture group
^|[.!?]\s # match ^ or (|) any of ([]) ., ! or ?, then one whitespace char
) # end non-capture group
\s* # match any number of whitespace chars
\K # forget the preceding match
[A-Z] # match one capital letter
/x
a = str.scan(r)
#=> ["I", "O"]
a.length
#=> 2
您可以使用别名size
或Array#length代替Array#count。
答案 3 :(得分:0)
您可以计算出有多少资本化,例如:
a = "Hello there. this is the best class. but does not offer anything."
a_sentence = a.split(".")
a_sentence.inject(0) { |sum, s| s.strip!; s.capitalize!.nil? ? sum += 1 : sum }
# => 1
a_sentence
# => ["Hello there", "This is the best class", "But does not offer anything"]
然后将它重新组合在一起,就像这样:
"#{a_sentence.join('. ')}."
# => "Hello there. This is the best class. But does not offer anything."
修改强>
@Humza sugested时,您可以使用count
:
a_sentence.count { |s| s.strip!; s.capitalize!.nil? }
# => 1