Python 代码:读取文件夹文件并统计词频
这段代码实现的功能是读取指定文件夹 'test-spam-1' 内的所有文件,对每个文件进行分词,并将分词结果添加到给定的字典 (dict0) 中。如果分词结果已经存在于字典中,则将对应键的值加 1。
具体代码如下:
def add_spam_dict_1(dict0):
pathDir = os.listdir('test-spam-1')
for s in pathDir:
new_dir = os.path.join('test-spam-1', s) # 将文件命加入到当前文件路径后面
if os.path.isfile(new_dir): # 如果是文件
with open(new_dir, 'r') as f:
dict_word = mail.mail_api(f)
time_str = list(jieba.cut(dict_word))
for i in time_str:
if i in dict0.keys(): # 待加入过滤规则
dict0[i] = int(dict0[i]) + 1
pass
return dict0
代码解释:
os.listdir('test-spam-1'): 获取 'test-spam-1' 文件夹下的所有文件名。- 循环遍历所有文件名,使用
os.path.join('test-spam-1', s)获取文件的完整路径。 - 使用
os.path.isfile(new_dir)判断当前路径是否指向文件。 - 如果是文件,则使用
with open(new_dir, 'r') as f打开文件进行读取。 mail.mail_api(f): 使用 mail 模块中的 mail_api 函数对文件内容进行处理,得到文本信息。- 使用 jieba 库进行分词,得到词语列表
time_str。 - 遍历分词结果
time_str,如果词语存在于字典dict0中,则将对应键的值加 1。 - 最终返回更新后的字典
dict0。
这段代码可以用于统计 'test-spam-1' 文件夹中所有文件的分词结果频率,并存储在字典 dict0 中。可以根据实际需要修改过滤规则,例如,可以过滤掉一些常见的词语或停用词。
原文地址: https://www.cveoy.top/t/topic/ocpN 著作权归作者所有。请勿转载和采集!