您的位置:首页 > 其它

Recipe 1.9. Processing a String One Word at a Time

2009-11-09 12:34 477 查看
1 class String
2 def word_count
3 frequencies = Hash.new(0)
4 downcase.scan(/\w+/) { |word| frequencies[word] += 1 }
5 return frequencies
6 end
7 end
8
9 puts %{Dogs dogs dog dog dogs.}.word_count
Output: dogs3dog2

Code
1 class String
2 def word_count
3 frequencies = Hash.new(0)
4 downcase.scan(/(\w+([-'.]\w+)*)/) { |word, ignore| frequencies[word] += 1 }
5 return frequencies
6 end
7 end
8
9 puts %{Dogs dogs dog dog dogs.}.word_count
10 puts %{"That F.B.I. fella--he's quite the man-about-town."}.word_count
Output: dogs3dog2
   quite1f.b.i1the1fella1that1man-about-town1he's1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐