python-統(tǒng)計英文文本文件中每個單詞出現(xiàn)的頻率

# -*- 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文本文件中

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容