计算 Ruby 中每个句子的单词数

Count Number of Words on Each Sentence in Ruby

如果你有一堆句子(一两段),你如何计算每个句子的字数。

string = "hello world.  Hello world."

#I first split sentences into an element like so, first maybe initialized variables to count sentence, then words within the sentence
sentencecount = 0
wordcount = 0

string.split(".").each do |sentence|
  sentencecount += 1                     #track number of sentence
  sentence.(/\W+/).each do |word|
    wordcount += 1                       #to track number of word
  end

  puts "Sentence #{sentencecount} has #{wordcount} words."

end

输出:

Sentence 1 has 2 words
Sentence 2 has 5 words

第二行应该说 2 个词而不是 5 个。有什么想法吗?是的,两个循环。也许有更好的方法来做到这一点,但这是我对程序的理解。

在每个句子后将 wordcount 重置为 0。

string = "hello world.  Hello world."

#I first split sentences into an element like so, first maybe initialized variables to count sentence, then words within the sentence
sentencecount = 0
wordcount = 0

string.split(".").each do |sentence|
  wordcount = 0
  sentencecount += 1                     #track number of sentences
  sentence.split(/\w+/).each do |word|
    wordcount += 1                       #to track number of words
  end

  puts "Sentence #{sentencecount} has #{wordcount} words."

end

你可以用space字符调用split来统计字数:

string = "hello world.  Hello world."

string.split(".").each_with_index do |sentence,index|
  puts "Sentence #{index+1} has #{sentence.split(" ").count} words."
end

# => Sentence 1 has 2 words.
# => Sentence 2 has 2 words.