# -*- coding:utf-8*-
"""
統(tǒng)計一篇英語文章中每個單詞出現(xiàn)的次數(shù)
"""
import string
def get_dict_word_times(file):
? ? """構建字典{單詞: 次數(shù)}"""
? ? list_word_with_punctuation = file.read().split()
? ? # 去掉標點,不區(qū)分大小寫
? ? 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('test.txt', 'r') as file:
#在該文件夾下打開英文文本文件test.txt, 把英文文章放在test.txt中
? ? ? ? dict_word_times = get_dict_word_times(file)
? ? # 把單詞按照次數(shù)由多到少排序
? ? 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()
#生成這個文件,然后將這個文件另存,編碼為utf-8
#然后在終端運行 python xx.py > res.txt
最終結果存在res.txt文本文件中