ruby - 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
解决方案
假设您需要计算单词而不是字符,我猜您希望将类称为:
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_string
whichcount_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
像以前一样打电话。
推荐阅读
- reactjs - 我如何准备 CRA 应用程序以部署到 heroku,我还需要像全栈 CRA 应用程序一样构建吗?
- php - PHP sqlsrv_query() 期望参数 1 是资源,
- python - Azure 数据湖 - 使用 Python 读取
- python - 使用 Python 和 Selenium 验证 url
- excel - 将动态列中的不同值获取到另一个工作表中
- java - 无法在应用程序之外解析 ContentProvider
- windows - 使用 terraform 在 vsphere_virtual_machine 上创建 windows 目录
- mysql - 如何转换此 SQL Select 查询以对结果集的表值执行更新?
- html - 当父级溢出时如何使子级div占用所有水平空间:滚动
- php - 如何使用 PHP 检查文本文件中的字符串重复项?