Ruby中txtfile中最长的单词 [英] Ruby longest word in txtfile
问题描述
我是ruby的新手,并选择了自学课程来扩展现有语言。我买了一本书,但是这些例子是如此模糊和写得很糟糕,你可以通过复制它们来完全没用。
伙计们,下面是打开文件的脚本分裂单词并对它们进行散列。然后显示每个单词出现的次数
words = File.open('my_text.txt'){| f | f.read} .split
freqs = Hash.new(0)
words.each {| word | freqs [word] + = 1}
freqs.sort_by {| x,y | y} .reverse.each {| w,f |放w +''+ f.to_s}
我想要实现的是找到这个txt文件中最长的单词,我似乎无法做到,有任何建议或指向正确的方向吗?
我的书中的例子:
longest = %w {cat sheep bear} .inject do | memo,word | memo.length> word.length?备注:单词
结束
不能把哈希放到这里,尝试过多种方式,它只是抛出错误
Im new to ruby, and have chosen a self learning course for expanding on current languages. I bought a book but the examples are so vague and badly written that you can pull nothing use full from copying them.
guys, below is a script for opening a file spliting the words and hashing them. then displaying how many times each word appears
words = File.open('my_text.txt') {|f| f.read }.split
freqs=Hash.new(0)
words.each { |word| freqs[word] += 1 }
freqs.sort_by {|x,y| y }.reverse.each {|w, f| puts w+' '+f.to_s}
what im trying to achieve is finding the 'longest' word in this txt file, i just cant seem to do it, any suggestions or a point in the right direction please?
example from my book:
longest = %w{ cat sheep bear }.inject do |memo,word| memo.length > word.length ? memo : word
end
cannot put the hash into this, have tried multiple ways, it just throws errors
推荐答案
解决了:
比我想象的要明显得多,2个frikkin天让我弄清楚你可以加载文件,拆分paragrahs / words然后对它们进行排序.....
solved:
was a bit more obvious than i thought, 2 frikkin days it took me to work out that you can load the file, split the paragrahs/words and then sort them.....
longest = File.open('my_text.txt') {|f| f.read }.split.inject do |memo,word| memo.length > word.length ? memo : word
end
longest
下一期是添加一些注册表来过滤符号
问候
Next issue is to add some reg ex to filter out symbols
regards
这篇关于Ruby中txtfile中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!