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

import os
#  os 模块提供了非常丰富的方法用来处理文件和目录。详细方法请参考菜鸟教程。
import re
re模块为正则表达式模块


def findWord(DirPath):
#  定义  ******函数
    if not os.path.isdir(DirPath):
    #  os.path.isdir()  判断路径是否为目录
        return
    fileList = os.listdir(DirPath)
    #  os.listdir(DirPath) 返回Dirpath指定的文件夹包含的文件或文件夹的名字的列表。
    reObj = re.compile('\b?(\w+)\b?')
    compile 函数用于编译正则表达式,生成一个正则表达式对象,供 match() 和 search() 这两个函数使用

    for file in fileList:
    # 遍历文件列表
        filePath = os.path.join(DirPath, file)
        #  	把目录和文件名合成一个路径
        if os.path.isfile(filePath) and os.path.splitext(filePath)[1] == '.txt':
        #  	判断路径是否为文件  并且分割路径,返回路径名和文件扩展名的元组
            with open(filePath) as f:
                data = f.read()
                # 读取文件内容
                words = reObj.findall(data)
                wordDict = dict()
                for word in words:
                    word = word.lower()
                    #  所有内容小写
                    if word in ['a', 'the', 'to',‘and’, ‘but’, 'or']:
                        continue
                    if word in wordDict:
                        wordDict[word] += 1
                    else:
                        wordDict[word] = 1
            ansList = sorted(wordDict.items(), key=lambda t: t[1], reverse=True)
            print('file: %s->the most word: %s' % (file, ansList[1]))


if __name__ == '__main__':
    findWord('source/0006')

猜你喜欢

转载自blog.csdn.net/shifanfashi/article/details/89402302