Ruby -- Capitalize First Letter of Every Sentence in a Paragraph

How to capitalize first character of each sentence in rails model

class Question < ActiveRecord::Base
before_save :capitalize_attributes

def capitalize_attributes
self.question = capitalize_sentences(question)
self.description = capitalize_sentences(description)
end

def capitalize_sentences(string)
unless string.blank?
string.split('.').map do |sentence|
sentence.strip.capitalize
end.join(' ')
end
end
end

Count capitalized of each sentence in a paragraph Ruby

Try this:

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

Ruby capitalize every word first letter

try this:

puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')

#=> One Two Three Four

or

puts 'one TWO three foUR'.split.map(&:capitalize)*' '

Change last character of every word in a sentence to a capital using Ruby

here's a quick and dirty regex method that's sure to be broken in ways I haven't considered:

"the quick brown fox jumps over the lazy dog".gsub(/.\b/) { |m| m.upcase }

i.e. upcase the last character match before a word boundary.

Titileize method to capitalize large words in titles

Because q[0] is "the", so when i is "the", it satisfies the condition:

i == q[0]

A better way to do it is:

Little = %w[over the and]
def titleize s
s.gsub(/\w+/)
.with_index{|w, i| i.zero? || Little.include?(w).! ? w.capitalize : w}
end

titleize("the bridge over the river kwai")
# => "The Bridge over the River Kwai"

How to capitalize the first character of each word, or the first character of a whole string, with C#?

As discussed in the comments of @miguel's answer, you can use TextInfo.ToTitleCase which has been available since .NET 1.1. Here is some code corresponding to your example:

string lipsum1 = "Lorem lipsum et";

// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;

// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}",
lipsum1,
textInfo.ToTitleCase( lipsum1 ));

// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et

It will ignore casing things that are all caps such as "LOREM LIPSUM ET" because it is taking care of cases if acronyms are in text so that "IEEE" (Institute of Electrical and Electronics Engineers) won't become "ieee" or "Ieee".

However if you only want to capitalize the first character you can do the solution that is over here… or you could just split the string and capitalize the first one in the list:

string lipsum2 = "Lorem Lipsum Et";

string lipsum2lower = textInfo.ToLower(lipsum2);

string[] lipsum2split = lipsum2lower.Split(' ');

bool first = true;

foreach (string s in lipsum2split)
{
if (first)
{
Console.Write("{0} ", textInfo.ToTitleCase(s));
first = false;
}
else
{
Console.Write("{0} ", s);
}
}

// Will output: Lorem lipsum et

Rails gem to break a paragraph into series of sentences

There are two non-trivial tasks to achieve what you are after:

  1. splitting a string into sentences
  2. and word-wrapping each sentence with extra care for punctuation.

I think the first one is not easy to implement from scratch so your best bet might just be to use natural language processing libraries provided that your "third-party language processing service" doesn't have such a feature. I don't know any "rails gem" to meet your requirement.

Here is just a toy example of splitting a string into sentences using stanford-core-nlp.

require 'stanford-core-nlp'
text = "Lorem ipsum, consectetur elit. Donec ut ligula. Sed acumsan posuere tristique. Sed et tristique sem. Aenean sollicitudin, sapien sodales elementum blandit. Fusce urna libero blandit eu aliquet ac rutrum vel tortor."
pipeline = StanfordCoreNLP.load(:tokenize, :ssplit)
a = StanfordCoreNLP::Annotation.new(text)
pipeline.annotate(a)
sentenses = a.get(:sentences).to_a.map &:to_s # Map with to_s if you want an array of sentence string.
# => ["Lorem ipsum, consectetur elit.", "Donec ut ligula.", "Sed acumsan posuere tristique.", "Sed et tristique sem.", "Aenean sollicitudin, sapien sodales elementum blandit.", "Fusce urna libero blandit eu aliquet ac rutrum vel tortor."]

The second problem is similar to word-wrapping and if it exactly were a word-wrapping problem, it should be easily solved using existing implementations like ActionView::Helpers::TextHelper.word_wrap.
However, there is an extra requirement concerning punctuations. I don't know any existing implementation to achieve exactly the same goal of yours. Maybe you have to come up with your own solution.

My only idea is to firstly word-wrap each sentence, secondly split each line with a punctuation and then join the pieces again but with limitation on length. I wonder if this would work though.

Ruby creating title case method, can't handle words like McDuff or McComb

There are several issues with your "Mc" code:

if (word.include?("mc"))

This will always return false, because you have already capitalized word. It has to be:

if word.include?('Mc')

This line doesn't work either:

letter_array = word.split!("")

because there is no split! method, just split. There is however no reason to use a character array at all. String#[] allows you to access a string's characters (or sub-strings), so the next line becomes:

if (word[0] == 'M') && (word[1] == 'c')

or just:

if word[0, 2] == 'Mc'

or even better using start_with?:

if word.start_with?('Mc')

In fact, we can replace the first if with this one.

The next line is a bit tricky:

letter_array[2].capitalize!

Using String#[] this becomes:

word[2].capitalize!

But unfortunately, both don't work as expected. This is because [] returns a new object, so the bang method doesn't change the original object. Instead you have to call the element assignment method []=:

word[2] = word[2].upcase

Everything put together:

if word.start_with?('Mc')
word[2] = word[2].upcase
end

Or in a single line:

word[2] = word[2].upcase if word.start_with?('Mc')


Related Topics



Leave a reply



Submit