第 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)