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

时间:2015-03-30 05:22:15

标签: ruby string loops count

如果你有一堆句子(一段或两段),你如何计算每个句子上的单词。

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.有什么想法?是的两个循环。也许有更好的方法可以做到这一点,但这就是我理解该计划的方式。

2 个答案:

答案 0 :(得分:2)

每句话后将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

答案 1 :(得分:2)

您可以使用空格字符调用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.