首页 > 解决方案 > word_count(s) > 计算文本中字母的作业

问题描述

我的作业是计算字符串中的字母,无论大小写如何......到目前为止我有这个我仍然无法让它工作,想法?

def self.word_count_from_file(filename)
    s = File.open(filename) { |file| file.read }
    word_count(s)
end

def self.words_from_string(s)
    s.downcase.scan(/[\w']+/)
end

def self.count_frequency(character)
    counts = Hash.new(0)
    for chatacter in characters
        counts[character] += 1
    end
    # counts.to_a.sort {|a,b| b[1] <=> a[1]}
    # sort by decreasing count, then lexicographically
    counts.to_a.sort do |a,b|
        [b[1],a[0]] <=> [a[1],b[0]]
    end
end

标签: ruby

解决方案


假设您需要计算单词而不是字符,我猜您希望将类称为:

WordCount.word_count_from_string('Words from this string of words')

或者

WordCount.word_count_from_file('filename.txt')

然后你需要两个类方法调用其他方法才能得到结果。因此,这是使其工作的一种选择:

class WordCount
    def self.word_count_from_file(filename)
        s =  File.open(filename) { |file| file.read }
        count_frequency(s)
    end

    def self.word_count_from_string(s)
        count_frequency(s)
    end

    def self.words_array(s)
        s.downcase.scan(/[\w']+/)
    end

    def self.count_frequency(s)
        counts = Hash.new(0)
        for character in words_array(s) # <-- there were a typo
            counts[character] += 1
        end
        counts.to_a.sort do |a,b|
            [b[1],a[0]] <=> [a[1],b[0]]
        end
    end
end

WordCount.word_count_from_string('Words from this string of words')
#=> [["words", 2], ["from", 1], ["of", 1], ["string", 1], ["this", 1]]
WordCount.word_count_from_file('word-count.txt')
#=> [["words", 2], ["this", 1], ["in", 1], ["of", 1], ["string", 1], ["a", 1], ["from", 1], ["file", 1]]

请注意,两者都word_count_from_file调用word_count_from_stringwhichcount_frequency调用words_array以获取和返回结果。


为了更加 Ruby-ish ( each) 和更少 Pythonic ( for),这是一个使用实例变量 ( ) 的替代版本@s,以避免传递参数(count_frequency而不是count_frequency(s)等)。

class WordCount
    def self.word_count_from_file(filename)
        @s = File.open(filename) { |file| file.read }
        count_frequency
    end

    def self.word_count_from_string(str)
        @s = str
        count_frequency
    end

    def self.count_frequency
        words_array.each_with_object(Hash.new(0)) { |word, cnt| cnt[word] += 1 }.sort_by(&:last).reverse
    end

    def self.words_array
        @s.downcase.scan(/[\w']+/)
    end
end

像以前一样打电话。


推荐阅读