【问题标题】:How to sort my output form my program without changing the order of my whole loop?如何在不改变整个循环顺序的情况下对我的程序输出进行排序?
【发布时间】:2022-11-26 08:10:44
【问题描述】:

我有这段代码:

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

它打印 txt 文件中最常见的单词。它输出这个:

The following words appeared 8 times each: what, just, apple

我希望“每个:”之后的输出按字母顺序排序而不更改打印顺序。我怎样才能做到这一点?谢谢! 是这样的:

The following words appeared 8 times each: apple, just, what

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    使用sorted

        print('The following words appeared %d times each: %s' % (count, ', '.join(sorted(counts_dict[count]))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 2018-11-16
      • 2023-03-28
      • 2020-11-12
      • 2012-11-20
      • 2021-05-12
      • 2011-05-20
      相关资源
      最近更新 更多