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
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
相关文章推荐
- Recipe 1.1. Processing a String One Character at a Time(Python Cookbook)
- Recipe 1.8. Processing a String One Character at a Time
- [Python]Processing a String One Character at a Time
- Error: "Database 'XXX' is already open and can only have one user at a time"
- uva 12726 One Friend at a Time bfs + 状态压缩
- Living one day at a time (update for a long time)
- Reason: Server is in single user mode. Only one administrator can connect at this time
- only one software management tool is allowed to run at the same time
- Makers at work:Folks Reinventing the World One Object or Idea at a Time
- UVa12726 one Friend at a Time (位 广搜)
- Python: keep strings in double quote as one word when split string to words
- Only one database connection at a time is supported
- iOS使用XIB文件报错:reason: 'A view can only be associated with at most one view controller at a time!
- 效率提升最重要的原则 - Doing one thing at a time
- vss 2005 提示 Only one database connection at a time is supported的处理
- How to read a whole document content into a string one-time
- Freemarker Failed at: ${itm.creatTimeString?string("yyyy-MM... [in template
- Sharepoint Service Error: A deployment or retraction is already under way for the solution "xxx.wsp" , and only one deployment or retraction at a time
- phpmyadmin登录报错crypt_random_string requires at least one symmetric cipher be loaded 解决方法
- Windows Mobile Development Making a quality platform one application at a time(zhuan)