您的位置:首页 > 编程语言 > Python开发

python 统计一篇英语文章中每个单词出现的次数

2019-06-13 11:59 746 查看
[code]"""
统计一篇英语文章中每个单词出现的次数
"""
import string

def get_dict_word_times(file):
"""构建字典{单词: 次数}"""

list_word_with_punctuation = file.read().split()
# 去掉标点,不区分大小写
list_word = [word.strip(string.punctuation).lower() for word in list_word_with_punctuation]
# 去掉重复单词
set_word = set(list_word)

return {word: list_word.count(word) for word in set_word}

def main():
with open('demo.txt', 'r') as file:
dict_word_times = get_dict_word_times(file)

# 把单词按照次数由多到少排序
list_sorted_words = sorted(dict_word_times, key=lambda w: dict_word_times[w], reverse=True)
for word in list_sorted_words:
print("{} -- {} times".format(word, dict_word_times[word]))

main()

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐