【问题标题】:Ruby simple Array/Iterator?Ruby 简单的数组/迭代器?
【发布时间】:2017-01-19 13:16:42
【问题描述】:

我有一个写在 .txt 文件中的故事,我必须计算字母和单词的数量,然后将两者除以求平均值。我找不到字母总数或单词总数。当我运行我的程序时,Ruby 向我显示了一个数字列表,但我认为这是每个单词的字母数。我正在寻找 TOTAL 字母,所以我不确定如何让 Ruby 添加所有内容。这是代码。也是计算单词总数“.count”的迭代器吗?

myfile = File.new("story.txt", "r")
contents = myfile.read
wordlist = contents.split
wordlist.each do |length|
puts length.size.to_s
end

【问题讨论】:

标签: ruby


【解决方案1】:

也是计算单词总数“.count”的迭代器?

没有。 count() 是一个 String 方法,您可以在 String docs 中了解它。

另一方面,each() 是一个迭代器。

您可以获取字符串的lengthsize,在String docs 中有描述。

所以,你可以这样做:

words = %w[ a to cat ]  #shortcut for ["a", "to", "cat"]
                        #Saves you from having to type all those quotes.
letter_count = 0
word_count = 0

words.each do |word|
  word_count += 1
  letter_count += word.length
end

puts "The count of words is: #{word_count}"
puts "The total number of letters is: #{letter_count}"

--output:--
The count of words is: 3
The total number of letters is: 6

【讨论】:

    【解决方案2】:

    母狗,

    如果您想从 .txt 文件中获取字母和单词的总数,您可以简单地使用 Ruby 字符串类中的 .split() 方法,该方法是 myfile.read 的返回值。

    要获取story.txt中所有字母的计数,我们可以使用

    contents.split("")

    我们给 split 方法.split()' 一个空字符串作为参数告诉 Ruby 将该字符串拆分为尽可能多的部分。

    contents.split("") 返回如下内容:

    => ["t", "h", "i", "s", " ", "i", "s", " ", "a", "n", " ", "e", "x", "a", "m", "p", "l", "e", " ", "s", "t", "o", "r", "y"]是吗?

    所以接下来我们使用.split() 方法来完成这些事情,它返回一个数组,我们可以在该数组上调用Array 类的.length 方法。 .length 方法返回数组中元素的数量。 在这种情况下,我们得到 => 24

    对于字数统计,我们将重复上述过程,只是我们将 ruby​​ 告诉split(" "),并在引用中使用" " 一个空格。

    所以要获得 .txt 中的字数和字母数,我们可以写类似

    myfile = File.new("file.txt", "r")
    contents = myfile.read
    word_list = contents.split(" ")#returns an array of words
    word_count = word_list.length# returns number all words in the text file
    letter_list = contents.split("")#returns an array of letters
    letter_count = letter_list.length#returns number of all letters in the text file
    

    【讨论】:

    • 此代码有效!是否可以在“for”循环中完成这项工作?
    • 当然,我推荐 Ruby 的 .each() 方法。它基本上是一个 for 循环,但包含 Ruby 必须提供的所有语法糖。一个例子可能是:word_list.each {|word| word_count += word.length }
    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    相关资源
    最近更新 更多