母狗,
如果您想从 .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