如何保持输出行顺序不变,对同频次统计单词按字母排序?
如何让高频单词统计结果中同频次单词按字母顺序排列
我编写了一段用于统计文本文件中高频单词的Python代码:
words = open(input('Enter the name of the file: ')).read().lower().split() number_of_words = int(input('Enter how many top words you want to see: ')) uniques = [] stop_words = ["a", "an", "and", "in", "is"] for word in words: check_special = False if word.isalnum(): check_special = True if word not in uniques and word not in stop_words and check_special: uniques.append(word) counts = [] for unique in uniques: count = 0 for word in words: if word == unique: count += 1 counts.append((count, unique)) counts.sort() counts.reverse() counts_dict = {count: [] for count, word in counts} for count, word in counts: counts_dict[count].append(word) sorted_count = sorted(counts_dict) count_num_word = 0 for count in counts_dict: if count_num_word >= number_of_words: break print('The following words appeared %d times each: %s' % (count, ', '.join(counts_dict[count]))) count_num_word += 1
当前输出示例:
The following words appeared 8 times each: what, just, apple
我希望在不改变输出行顺序(仍按频次从高到低排列)的前提下,将每行“each:”后的单词按字母顺序排列,得到如下输出:
The following words appeared 8 times each: apple, just, what
解决方案
有两种简单的实现方式:
方式一:提前对每个频次的单词列表排序
在构建完counts_dict之后,添加一段循环对每个频次对应的单词列表进行字母排序:
# 在for count, word in counts:循环之后,输出循环之前添加 for count in counts_dict: counts_dict[count].sort()
修改后的完整代码片段:
counts_dict = {count: [] for count, word in counts} for count, word in counts: counts_dict[count].append(word) sorted_count = sorted(counts_dict) # 新增排序逻辑 for count in counts_dict: counts_dict[count].sort() count_num_word = 0 for count in counts_dict: if count_num_word >= number_of_words: break print('The following words appeared %d times each: %s' % (count, ', '.join(counts_dict[count]))) count_num_word += 1
方式二:输出时直接排序
不需要修改字典结构,直接在输出时对当前频次的单词列表进行排序:
将原print语句替换为:
print('The following words appeared %d times each: %s' % (count, ', '.join(sorted(counts_dict[count]))))
两种方式都能保证同频次单词按字母顺序排列,同时输出行仍保持按频次从高到低的顺序(Python 3.7及以上版本的字典会保留键的插入顺序,这里counts已经按频次降序排列,所以counts_dict的键顺序符合要求)。
内容的提问来源于stack exchange,提问作者thenorthape
相关产品推荐
相关产品推荐

