今天去面试,被问到如何实现词频统计,因为之前都是直接调用value_counts()函数统计,在被要求不用该函数实现统计,一紧张就卡壳了,回到家大概自己想了一下,怎么一步步复现。
实现的方法有多种,我才用的办法是先把文件处理成string类型,然后string处理函数
#读入文件并处理成文本
def read_file(text_file):
string_for_count=[]
with open(text_file) as wf:
for line in wf:
string_for_count.append(line)
return ''.join(string_for_count)
随后定义文本中词语的词频统计
#统计词频
def word_counts(string):
string_list = string.replace('\n','').lower().split(' ')
count_dic = {}
for item in string_list:
if item in count_dic.keys():
count_dic[item] += 1
else:
count_dic[item] = 1
if ' ' in count_dic:
count_dic.pop('') #删除空格
count_list = sorted(count_dic.iteritems(),key=lambda x: x[1],reverse=True)
return count_list
写的仓促,仅仅纪念惨淡的一次面试,以及渣渣的学习之路
在复习《机器学习实战》的时候,对于第二部分统计词频,获取到了使代码更简洁的表达方式,如下:
def word_counts(string):
string_list = string.replace('\n','').lower().split(' ')
count_list = {}
for item in string_list:
count_list[item] = count_list.get(item,0)+1
if ' ' in count_list:
count_list.pop('') #删除空格
count_list = sorted(count_list.items(),key=lambda x: x[1],reverse=True)
return count_list