1、原题

2、perl脚本

print "================ Method 1=====================\n";
open IN,'<','anna-karenina.txt';
while(<IN>){
chomp;
$line = $_;
$line =~ s/[ \. , ? ! ; : ' " ( ) { } \[ \]]/ /g; #句号,逗号等统一改为空格
#print("$line\n");
@words = split(/\s+/,$line);
foreach $word (@words){
$counts{lc($word)}++; #将出现的单词存入hash表
}
}; foreach $word (sort keys %counts) {
print "$word,$counts{$word}\n"; #打印出单词出现的个数
}
close IN; print "================ Method 2=====================\n";
open IN,'<','anna-karenina.txt';
while (my $line = <IN>)
{
#map{$words{$_}++;} $line =~ /(\w+)/g # 与下面的语句等效 #print($line =~ /(\w+)/g);
foreach ($line =~ /(\w+)/g){ # 对单词进行匹配
#print("$_\n");
$words{lc($_)}++;
}
}
for (sort keys(%words))
{
print "$_: $words{$_}\n";
}

3、结果

1)测试文本

All happy families resemble one another; every unhappy family is unhappy in its own way.
All was confusion in the house of Oblonskys. happy? happy: [happy] {happy} "happy" 'happy'

2)输出

================ Method =====================
all,
another,
confusion,
every,
families,
family,
happy,
house,
in,
is,
its,
oblonskys,
of,
one,
own,
resemble,
the,
unhappy,
was,
way,
================ Method =====================
all:
another:
confusion:
every:
families:
family:
happy:
house:
in:
is:
its:
oblonskys:
of:
one:
own:
resemble:
the:
unhappy:
was:
way:

4、涉及的知识点

1)对多个项目进行替换可以使用方括号:

  $line =~ s/[ \. , ? ! ; : ' " ( ) { }  \[ \]]/ /g; #句号,逗号等统一改为空格

2)将单词小写lc,用哈希计数

  $counts{lc($word)}++;  #将出现的单词存入hash表

3)访问哈希整体%,访问哈希键值keys %,排序sort

  sort keys %counts

4)方法2使用  $line =~ /(\w+)/g  直接将文本中的单词转换成列表

最新文章

  1. OVS 中的各种网络设备 - 每天5分钟玩转 OpenStack(128)
  2. oslo.messaging 1.8.0 bug fix and blueprint
  3. 配置rt-thread开发环境(配置系统,生成系统镜像)
  4. JavaScript基础10——node对象
  5. django学习日志之自定义用户扩展
  6. hdu 2881 Jack&#39;s struggle(DP)
  7. URI URL
  8. 从setTimeout到浏览器线程机制
  9. Binary Tree Inorder Traversal(转)
  10. MFC的核心概念
  11. 第二章:JavaScript对象
  12. jQuery Mobile事件,开发全解+完美注释
  13. [Swift]LeetCode71. 简化路径 | Simplify Path
  14. [译]迁移到新的 React Context Api
  15. Centos6.5部署Rsyslog+LogAnalyzer中文乱码解决
  16. webservice接口测试wsdl
  17. MFC笔记5
  18. 小程序 login
  19. Java调用Lua脚本(热载实现)
  20. Codeforces Round #539&amp;#542&amp;#543&amp;#545 (Div. 1) 简要题解

热门文章

  1. Ceph 存储集群4-高级运维:
  2. AWS的边缘计算平台GreenGrass和IoT
  3. 【原创】为什么Mongodb索引用B树,而Mysql用B+树?
  4. CERC2017 H Hidden Hierarchy(树+模拟)
  5. gulp 压缩文件2 摘
  6. 二. 大数据常用的算法和数据结构 &lt;&lt;大数据日知录&gt;&gt; 读书笔记
  7. 四步搞定Zabbix 日志文件监控
  8. VFP CursorAdapter 起步二(作者:Doug Hennig 译者:fbilo)
  9. 大延时情况tcp和udp测试
  10. 修改定时清理 /tmp 目录下的文件