Codewars题解:返回出现频次Top3单词的Python实现
Codewars 编程题:统计文本中出现频次最高的前3个单词
题目要求
编写功能函数,输入为一段文本,输出为文本中出现次数排名前三的单词组成的数组。
对应Python实现
代码导入re正则模块处理单词匹配规则,通过递归逻辑逐轮筛选当前剩余单词列表里的最高频词,最后清理结果中的空值后返回:
import re def find_top_word(top, word_list, word_set): top_word = '' top_count = 0 for word in word_set: counter = 0 for char in word_list: if word == char: counter += 1 if counter > top_count: top_word = word top_count = counter top.append(top_word) while top_word in word_list: word_list.remove(top_word) if len(top) < 3: find_top_word(top, word_list, word_set) def top_3_words(word): top = [] word_list = [str(re.findall(r'\b(\w+.\w+)\b', char.lower()))[2:-2] if "'" in char else str(re.findall(r'\b\w+\b', char.lower()))[2:-2] for char in word.split()] word_set = set(word_list) find_top_word(top, word_list, word_set) for word in top: if word == '': del top[top.index(word)] if top[0] == '': del top[0] print(top) return top
内容的提问来源于stack exchange,提问作者Дима Онуфриенко
相关产品推荐
相关产品推荐

