PythonShowMeTheCode(0004): 检查单词个数

1. 题目

第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。

2. 效果

#------1.txt-----------
  There are moments in life when you miss only
 one life and one chance to do
 you want to do.is 
isn't don't word_d common

#------输出------------
do: 2
word_d: 1
want: 1
to: 2
is: 1
you: 2
isn't: 1
don't: 1
...
  • 将所有单词按照小写处理
  • isn'tword_d这种应当作为一个单词

3. 实现

# -*- coding:utf-8 -*-
import re


def get_word_dict(file_path=None):
    if file_path is None:
        print("Error")
        return

    word_dict = {}
    with open(file_path, "r", encoding="utf-8") as file:
        for line in file.readlines():
            words = re.findall(r"[a-z\'_-]+\b", line.lower())
            for word in words:
                if word not in word_dict:
                    word_dict[word] = 1
                else:
                    word_dict[word] += 1
    for word, count in word_dict.items():
        print("%s: %d\n" % (word, count))
    return word_dict


if __name__ == "__main__":
    get_word_dic("1.txt")

4. 解决问题

<i>I. 无法识别isn't这样的单词</i>
在正则匹配时需要在加入一个\b来作为单词边界。

<i>II. 读取文件出现编码错误</i>
open()函数中加入encoding参数。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,924评论 9 468
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,461评论 19 139
  • 命令历史 以:和/开头的命令都有历史纪录,可以首先键入:或/然后按上下箭头来选择某个历史命令。 启动vim 在命令...
    im蚂蚁阅读 30,937评论 3 48
  • 推荐几个正则表达式编辑器 Debuggex :https://www.debuggex.com/ PyRegex:...
    木易林1阅读 13,992评论 9 151
  • 文/阿拉猪 妹纸,我猜你最近肯定是这样,每天盼着周三周四,上班想着下班回去看宋仲基,扒遍宋仲基上过的综艺、演...
    米茶米茶阅读 3,385评论 2 0