博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Recipe 1.9. Processing a String One Word at a Time
阅读量:4514 次
发布时间:2019-06-08

本文共 657 字,大约阅读时间需要 2 分钟。

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

 

ContractedBlock.gif
ExpandedBlockStart.gif
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

 

转载于:https://www.cnblogs.com/zhtf2014/archive/2009/11/09/1598945.html

你可能感兴趣的文章
iOS 9检测QQ、微信是否安装
查看>>
对Excel或者其他office操作推荐使用NPOI
查看>>
Java内部类、静态嵌套类、局部内部类、匿名内部类
查看>>
tp5 + layui 上传图片[支持单张和多张 ]
查看>>
黑苹果快捷键
查看>>
rsa.FromXmlString 系统找不到指定的文件
查看>>
PCB 电测试--测试点数自动输出到流程指示中(读取TGZ Stephdr文件)
查看>>
模型分离(选做)
查看>>
java 中的异步回调
查看>>
linux 自动登录
查看>>
Java NIO3:缓冲区Buffer
查看>>
Linux格式化分区报错Could not start /dev/sda No such file or directory 解决办法
查看>>
Nlog Layout
查看>>
event事件的坐标 offsetWidth client scroll
查看>>
Python时间,日期,时间戳之间转换
查看>>
我悲惨的人生,该死的UPX壳,谁能救救我
查看>>
7种最有效的懒人减肥方法,收藏了!
查看>>
如何解决虚拟机安装centos无法全屏显示问题!
查看>>
内部跳转(请求转发)和外部跳转(重定向)的区别?
查看>>
GWT(Google Web Tookit) Eclipse Plugin的zip下载地址(同时提供GWT Designer下载地址)
查看>>