计算段落中每个句子的大写 Ruby

Count capitalized of each sentence in a paragraph Ruby

我回答了我自己的问题。忘记初始化count = 0

我在一个段落中有一堆句子。

  1. a = "Hello there. this is the best class. but does not offer anything."为例。
  2. 要弄清楚第一个字母是否大写,我的想法是 .split 字符串,以便 a_sentence = a.split(".")
  3. 我知道我可以 "hello world".capitalize! 所以如果它是 nil 对我来说意味着它已经大写了 编辑
  4. 现在我可以使用数组方法遍历值并使用'.capitalize!
  5. 而且我知道我可以检查是否有东西 .strip.capitalize!.nil?

但是我好像无法输出多少个大写。

编辑

 a_sentence.each do |sentence|
        if (sentence.strip.capitalize!.nil?)
            count += 1
            puts "#{count} capitalized"
        end
    end

它输出:

1 capitalized

感谢您的帮助。我将坚持使用我在 Ruby 中只知道的框架内可以理解的上述代码。 :)

试试这个:

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."

您的 post 的标题具有误导性,因为从您的代码来看,您似乎想要计算句子开头的大写字母数。

假设每个句子都以句号(句号)结尾,然后是 space,以下内容应该适合您:

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

你可以数出有多少个被大写了,像这样:

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 所说,您可以使用 count:

a_sentence.count { |s| s.strip!; s.capitalize!.nil? }
# => 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

而不是 Array#length, you could use its alias, size, or Array#count