Python 練習(xí)冊(cè)堰酿,每天一個(gè)小程序,原題來自Yixiaohan/show-me-the-code
我的代碼倉(cāng)庫(kù)在Github
目標(biāo)
你有一個(gè)目錄膜毁,放了你一個(gè)月的日記昭卓,都是 txt,為了避免分詞的問題瘟滨,假設(shè)內(nèi)容都是英文候醒,請(qǐng)統(tǒng)計(jì)出你認(rèn)為每篇日記最重要的詞。
解決方案
該題目代碼如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
你有一個(gè)目錄杂瘸,放了你一個(gè)月的日記倒淫,都是 txt,為了避免分詞的問題败玉,假設(shè)內(nèi)容都是英文敌土,請(qǐng)統(tǒng)計(jì)出你認(rèn)為每篇日記最重要的詞。
"""
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):
"""
根據(jù)文件路徑返干,找到文件中的關(guān)鍵字
: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 為關(guān)鍵詞血淌,共出現(xiàn)了 %s 次" % (name, results[-1][0], results[-1][1]))