1
1
# 封装d5的代码
2
2
import re
3
+ from collections import Counter
3
4
4
5
5
6
def clean_ip_list (words ): # 清理掉空格 标点符号
@@ -41,16 +42,18 @@ def list_dict(l):
41
42
return cadiz
42
43
43
44
44
- def stats_text_en (s ):
45
+ def stats_text_en (s , count ):
45
46
if isinstance (s , str ):
46
47
s = cut_clean (s ) # 切分字符串并清洗标点符号
47
48
s_dict = list_dict (s ) # 将tempiate转化为字典并统计词频
48
- # 对字典按照value值排序
49
- s_s_dict = sorted (s_dict .items (), key = lambda item : item [1 ], reverse = True )
50
- print (s_s_dict )
49
+ # 用Counter对数组按照value值排序
50
+ c_dict = Counter (s_dict )
51
+ # 找出频率最多的前count名
52
+ c_dict = c_dict .most_common (count )
53
+ print (c_dict )
51
54
else :
52
55
raise ValueError ("is not str" )
53
- return s_s_dict
56
+ return c_dict
54
57
55
58
56
59
def cut_count_cn (c , regex ): # 取出所有中文 是一个列表
@@ -67,18 +70,21 @@ def cut_count_cn(c, regex): # 取出所有中文 是一个列表
67
70
return cadiz
68
71
69
72
70
- def stats_text_cn (s ): # 定义检索中文函数
73
+ def stats_text_cn (s , count ): # 定义检索中文函数
71
74
if isinstance (s , str ):
72
75
regex = re .compile ("(?x)(?: [\w -]+ | [\x80 -\xff ]{3} )" )
73
76
words = cut_count_cn (s , regex )
74
- s_s_dict = sorted (words .items (), key = lambda item : item [1 ], reverse = True )
75
- print (s_s_dict )
77
+ # 用Counter对数组按照value值排序
78
+ c_dict = Counter (words )
79
+ # 找出频率最多的前count名
80
+ c_dict = c_dict .most_common (count )
81
+ print (c_dict )
76
82
else :
77
83
raise ValueError ("is not str" )
78
- return s_s_dict
84
+ return c_dict
79
85
80
86
81
87
# 定义stats_text函数
82
- def stats_text (s ):
83
- stats_text_cn (s ) # 导入stats_text_cn函数
84
- stats_text_en (s ) # 导入stats_text_en函数
88
+ def stats_text (s , count ):
89
+ stats_text_cn (s , count ) # 导入stats_text_cn函数
90
+ stats_text_en (s , count ) # 导入stats_text_en函数
0 commit comments