Ruby - 对段落中每个句子的首字母进行大写

4
使用Ruby语言,我想要将每个句子的第一个字母大写,并且去掉每个句子末尾句号前面的空格,不应该改变任何其他内容。
Input =  "this is the First Sentence . this is the Second Sentence ."    
Output =  "This is the First Sentence. This is the Second Sentence."

谢谢大家。

你如何定义“每个句子末尾的句点”?例如,在此字符串中哪些句点是“在句子末尾”的:“The . character is used in object oriented languages a lot. You might say Dog.bark, or Cat.meow, and even, in a very perverse language, Cow. (the method name is a space here.) Or you might not... ouch, stop hitting me.” - sameers
2个回答

7
使用正则表达式(String#gsub):
Input =  "this is the First Sentence . this is the Second Sentence ."    
Input.gsub(/[a-z][^.?!]*/) { |match| match[0].upcase + match[1..-1].rstrip }
# => "This is the First Sentence. This is the Second Sentence."

Input.gsub(/([a-z])([^.?!]*)/) { $1.upcase + $2.rstrip }  # Using capturing group
# => "This is the First Sentence. This is the Second Sentence."

我假设这句话以 ., ?, ! 结束。

更新

input = "TESTest me is agreat. testme 5 is awesome"
input.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip }
# => "TESTest me is agreat. Testme 5 is awesome"

input = "I'm headed to stackoverflow.com"
input.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip }
# => "I'm headed to stackoverflow.com"

@roytoy想要去掉所有句子末尾的句号之前的空格。 - Jun Zhou
如果字符串是 this is stackoverflow.com,那么 .com 将会变成 .Com - user3188544
@user3188544,另一种方法:'this is stackoverflow.com'.gsub(/(^|\s)([a-z])([^.?!]*)/) { $1 + $2.upcase + $3.rstrip } - falsetru
@falsetru 不完全正确... I'm headed to stackoverflow.com 应该翻译为 我正前往stackoverflow.com - user3188544
2
@user3188544,你是对的。这是另一个使用正向预查的替代方案:/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i - falsetru
显示剩余5条评论

1
Input.split('.').map(&:strip).map { |s|
  s[0].upcase + s[1..-1] + '.'
}.join(' ')
=> "This is the First Sentence. This is the Second Sentence."

我的第二种方法更加简洁,但会产生稍微不同的输出:

Input.split('.').map(&:strip).map(&:capitalize).join('. ') + '.'
=> "This is the first sentence. This is the second sentence."

我不确定你是否对此感到满意。


以问号结尾的句子怎么办?还有感叹号和问号同时结尾的句子呢? - Dhanu Gurung
不用担心句子以?或!结束。 - roytony
@ram 经过仔细阅读问题,我认为他可以假设每个句子都以句号结束。 - Jun Zhou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接