Python 练习册 6-统计文本文件中单词的次数

Python 练习册,每天一个小程序,原题来自Yixiaohan/show-me-the-code
我的代码仓库在Github

目标

你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。

解决方案

该题目代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
"""

import os
import re


def get_file_list(path):
    """
        遍历文件目录,返回文件路径列表
    """
    file_list = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.lower().endswith('txt'):
                file_list.append(os.path.join(root,file))
    return file_list


def find_keyword(file_path):
    """
    根据文件路径,找到文件中的关键字
    :param file_path:
    :return:
    """
    keywords = {}
    file_name = os.path.basename(file_path)
    with open(file_path, encoding='utf-8') as file:
        text = file.read()
        word_list = re.findall(r'[a-zA-Z]+', text.lower())
        for word in word_list:
            if word in keywords:
                keywords[word] += 1
            else:
                keywords[word] = 1
        keywords_sorted = sorted(keywords.items(), key=lambda d: d[1])
    return file_name, keywords_sorted

for path in get_file_list(os.getcwd()):
    name, results = find_keyword(path)
    print(u"在 %s 文件中,%s 为关键词,共出现了 %s 次" % (name, results[-1][0], results[-1][1]))
    原文作者:王鹏程Orange
    原文地址: https://www.jianshu.com/p/bf4dc3024f72
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞