Ruby 计算段落中每个句子的大写字母
我回答了我自己的问题。忘记初始化Ruby 计算段落中每个句子的大写字母,ruby,arrays,split,capitalize,Ruby,Arrays,Split,Capitalize,我回答了我自己的问题。忘记初始化count=0 我在一段中有一大堆句子 a=“您好。这是最好的课程。但不提供任何东西。”举个例子 要确定第一个字母是否大写,我的想法是.split字符串,以便a_句子=a.split(“.”) 我知道我可以“你好,世界”。大写因此,如果它是nil对我来说意味着它已经大写了 编辑 现在我可以使用数组方法遍历值并使用“.capitalize!” 我知道我可以检查是否有.strip.capitalize!。无? 但我似乎无法输出多少是资本化的 编辑 它输出: 1 cap
count=0
我在一段中有一大堆句子
a=“您好。这是最好的课程。但不提供任何东西。”
举个例子李>
.split
字符串,以便a_句子=a.split(“.”)
“你好,世界”。大写
因此,如果它是nil
对我来说意味着它已经大写了
编辑.capitalize!”代码>
.strip.capitalize!。无?
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."
b=[]
a、 拆分(“.”)。每个do |句|
您好,这是最好的课程,但不提供任何服务
你的文章标题有误导性,因为从你的代码中,你似乎想得到句子开头大写字母的数量
假设每个句子都以句号(句号)和空格结尾,那么以下内容对您来说应该有用:
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."
然后把它放回一起,像这样:
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
您可以使用它的别名,
size
或。出现此错误是因为您需要先定义count
。在使用count+=1
之前,尝试在循环外部添加count=0
。查看我的响应。您只需将一个块传递给count
,就可以让事情变得简单多了。@victorkohl是的,我喜欢一个句子。count{s | s.strip!;s.capitalize!.nil?}更好:)谢谢!