Python 练习册 6-找出重要的单词

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

一.准备

1.找出最重要的单词也就是找出一篇日记中出现次数最多的单词,其次为了打开这篇日记我们还涉及了文档的操作,所以我们只要在日记文件夹中依次打开每一篇日记,记录下每一篇日记中出现次数最多的单词,然后输出即可。

2.我们将会用到两个重要的方法
os.listdir()

os.listdir()#方法用于返回指定文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序,不包括‘.’和‘…’即使其在文件夹中。

#注意,返回的是目标文件夹中包含的文件或文件夹的名字,通常用于提取文件夹中文件,用一个循环遍历所有文件。

path =.............#path是目标文件夹的路径

for filename in os.listdir(path):# 遍历文件夹里的文件

collections.Counter().most_common()
可以直接统计出现最多的单词
~栗子来了

words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words)
# 出现频率最高的3个单词
top_three = word_counts.most_common(3) # 里面的这个参数表示从上到下你想要统计单词的个数,也就是你想要前几名
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]

二.完成

''''''
第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词
''''''
from collections import  Counter
import os
def get_diary_path():
    list=[]
    dir_path = '.......'# 用你想的文件目录代替
    for path in os.listdir(dir_path):
        list.append(dir_path+'/'+path)
    return list
def cout_mostcommon_words(paths):
    common_words = []
    for path in paths:
        words = []
        with open(path,'r') as f:以只读方式打开每一个txt文件
            for line in f :
                line = line.strip('\n')去掉换行
                if line != '':#去掉空格
                    split = str(line).strip(' ')
                    words.extend(split)
        common_word = Counter(words).most_common(1) #获取出现词汇最多的
        common_words.append(common_word)
    return common_words


if __name__ == '__main__':
    paths=get_diary_path()
    words = cout_mostcommon_words(paths)
    print(words)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

おもいね

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值