第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数

第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数

import re
from collections import Counter

def create_list(file):
    with open(file) as f:
        f_list = []
        for line in f:
            text = re.sub('\"|\.|,',"",line)  #去掉“ , .
            line_list = text.strip().split(' ')
            print(line_list)
            f_list.extend(line_list)  # list.extend() 往列表中一次添加多个元素
        return f_list

# 使用collections.Counter
def get_count1(file):
    f_list = create_list(file)
    print(Counter(f_list))
    print(Counter(f_list).most_common(1))
    return Counter(f_list)

# 使用re.findall()
def get_count2(file):
    result = {}
    f_list = create_list(file)  #获取整个文章所有词的list
    f_str = ' '.join(f_list) + ' '  # 将所有词组成一个长字符串,每个单词用空格隔开
    print(f_str)
    word_list = list(set(f_list))     #去掉重复单词的列表
    print(word_list)
    for w in word_list:
        find_list = re.findall(w+' ',f_str)    # 查找所单词在长字符串中是出现的次数,返回list['and', 'and', 'and', 'and']
        result[w] = len(find_list)
    print(result)
    return result



if __name__ == "__main__":
    c1 = get_count1('0004.txt')
    c2 = get_count2('0004.txt')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值