这个Ruby应用程序如何知道选择中间三分之一的句子?
我目前正在学习Peter Cooper的入门Ruby,并且已经开发了我的第一个应用程序,一个文本分析器。然而,虽然我了解所有概念及其工作方式,但我始终无法理解应用程序如何从这行中选择按长度排序的中间三分之一的句子:这个Ruby应用程序如何知道选择中间三分之一的句子?,ruby,slice,Ruby,Slice,我目前正在学习Peter Cooper的入门Ruby,并且已经开发了我的第一个应用程序,一个文本分析器。然而,虽然我了解所有概念及其工作方式,但我始终无法理解应用程序如何从这行中选择按长度排序的中间三分之一的句子: ideal_sentances = sentences_sorted.slice(one_third, one_third + 1) 我已经包括了整个应用程序的背景下,任何帮助是非常感谢,因为到目前为止,一切都是有意义的 #analyzer.rb --Text Analyzer
ideal_sentances = sentences_sorted.slice(one_third, one_third + 1)
我已经包括了整个应用程序的背景下,任何帮助是非常感谢,因为到目前为止,一切都是有意义的
#analyzer.rb --Text Analyzer
stopwords = %w{the a by on for of are with just but and to the my I has some in do}
lines = File.readlines(ARGV[0])
line_count = lines.size
text = lines.join
#Count the characters
character_count = text.length
character_count_nospaces = text.gsub(/\s+/, '').length
#Count the words, sentances, and paragraphs
word_count = text.split.length
paragraph_count = text.split(/\n\n/).length
sentence_count = text.split(/\.|\?|!/).length
#Make a list of words in the text that aren't stop words,
#count them, and work out the percentage of non-stop words
#against all words
all_words = text.scan(/\w+/)
good_words = all_words.select {|word| !stopwords.include?(word)}
good_percentage = ((good_words.length.to_f / all_words.length.to_f)*100).to_i
#Summarize the text by cherry picking some choice sentances
sentances = text.gsub(/\s+/, ' ').strip.split(/\.|\?|!/)
sentances_sorted = sentences.sort_by { |sentence| sentance.length }
one_third = sentences_sorted.length / 3
ideal_sentances = sentences_sorted.slice(one_third, one_third + 1)
ideal_sentances = ideal_sentences.select{ |sentence| sentence =~ /is|are/ }
#Give analysis back to user
puts "#{line_count} lines"
puts "#{character_count} characters"
puts "#{character_count_nospaces} characters excluding spaces"
puts "#{word_count} words"
puts "#{paragraph_count} paragraphs"
puts "#{sentence_count} sentences"
puts "#{sentence_count / paragraph_count} sentences per paragraph (average)"
puts "#{word_count / sentence_count} words per sentence (average)"
puts "#{good_percentage}% of words are non-fluff words"
puts "Summary:\n\n" + ideal_sentences.join(". ")
puts "-- End of analysis."
很明显,我是一个初学者,所以简单的英语会帮助很大,干杯 它得到句子长度的三分之一,其中
三分之一=句子排序。长度/3
然后你发布的那行理想句子=句子排序。slice(三分之一,三分之一+1)
说“从索引等于三分之一开始,抓取所有句子的一个片段,然后继续长度+1的三分之一”
有意义吗?在ruby API中查找的slice方法如下所示: 如果传递了两个Fixnum对象,则返回从 偏移量由第一个给定,长度由第二个给定 这意味着如果你把一个句子分成三段
ONE | TWO | THREE
slice(1/3,1/3+1)
将返回从1/3开始的字符串
| TWO | THREE (this is what you are looking at now)
然后返回距离您所在位置1/3+1的字符串,这将为您提供
| TWO |
句子
是所有句子的列表sentances\u sorted
是按句子长度排序的列表,因此中间三分之一将是平均长度最大的句子slice()
从1/3
表示的位置开始,从该点开始计数1/3+1
请注意,正确的拼写是“句子”,而不是“句子”。我之所以提到这一点,只是因为您有一些代码错误,这些错误是由于拼写不一致造成的。当我第一次开始时,我也被困在这一点上。简单地说,您必须认识到slice方法在这里可以接受两个参数 第一个是索引。第二个问题是切片的长度 让我们假设你从6个句子开始。 三分之一=2 切片(三分之一,三分之一+1) 六分之一等于二 1) 这里的1/3表示从元素2开始,元素2是索引[1] 2) 然后再增加2(6/3)个+1长度,因此总共有3个空格
所以它影响着指数1到指数3我不理解这个问题。请发布你得到的结果和你期望的结果。