计算Ruby中每个句子的字数
如果你有一堆句子(一段或两段),你如何计算每个句子的字数 输出:计算Ruby中每个句子的字数,ruby,string,loops,count,Ruby,String,Loops,Count,如果你有一堆句子(一段或两段),你如何计算每个句子的字数 输出: Sentence 1 has 2 words Sentence 2 has 5 words 第二行应该说2个字,而不是5个字。有什么想法吗?是的,两个循环。也许有更好的方法可以做到这一点,但这就是我对程序的理解。在每个句子后将字数重置为0 string = "hello world. Hello world." #I first split sentences into an element like so, first m
Sentence 1 has 2 words
Sentence 2 has 5 words
第二行应该说2个字,而不是5个字。有什么想法吗?是的,两个循环。也许有更好的方法可以做到这一点,但这就是我对程序的理解。在每个句子后将
字数重置为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
每句话后将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
只需使用空格字符调用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.
只需使用空格字符调用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.
使用put..
打印结果后,您必须将wordcount
重置为0
。顺便问一下,这是一个什么方法的句子。(/\W+/)
?句子。拆分(/\W+/)类型在使用put..
打印结果后,您必须将wordcount
重置为0
。顺便问一下,这是一个什么方法的句子。(/\W+/)
?句子。拆分(/\W+/)你知道第二行为什么第2行有3个单词。因为W匹配非单词字符。使用W代替。我会更新答案。为什么知道第二行输出的句子2有3个单词。因为\w匹配非单词字符。使用w代替。我将更新答案。考虑<代码>分裂(/[!!?])<>代码>考虑<代码>拆分(/[!!])/代码>。