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

f = open("D:\Walden.txt","w")
f.close()
f = open("D:\Walden.txt","r")
f
<_io.TextIOWrapper name='D:\\Walden.txt' mode='r' encoding='cp936'>
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("D:\Walden.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()

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(“D:\Walden.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()

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值