第 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')
第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数
最新推荐文章于 2021-03-23 19:22:27 发布