首页 > 解决方案 > 输出未排序,无法对第二个值进行排序。是否有特殊方法对第二个值进行排序

问题描述

输出未排序,无法对第二列进行排序。是否有特殊方法对第二个值进行排序。

这个程序接受一个文本并计算一个单词在文本中出现的次数

import string
with open("romeo.txt") as file:  # opens the file with text
    lst = []
    d = dict ()
    uniquewords = open('romeo_unique.txt', 'w')
    for line in file:
        words = line.split()
        for word in words:  # loops through all words
            word = word.translate(str.maketrans('', '', string.punctuation)).upper()  #removes the punctuations
            if word not in d:
                d[word] =1
            else:
                d[word] = d[word] +1

            if word not in lst:
                lst.append(word)    # append only this unique word to the list
                uniquewords.write(str(word) + '\n') # write the unique word to the file
print(d)

标签: pythonsortingcounting

解决方案


具有默认值的字典

代码片段:

d = dict()
...
if word not in d:
    d[word] =1
else:
    d[word] = d[word] +1

在 python 中已经变得如此普遍,以至于创建了一个 dict 的子类来摆脱它。它按名称命名defaultdict,可以在 module 中找到collections

因此,我们可以将您的代码片段简化为:

from collections import defaultdict

d = defaultdict(int)
...
d[word] = d[word] + 1

无需手动if/else测试;如果word不在 defaultdict 中,则会自动添加,初始值为 0。

计数器

计算出现次数也经常有用。如此之多,以至于在 module中存在一个dict 的子类Countercollections。它将为您完成所有艰苦的工作。

from collections import Counter
import string

with open('romeo.txt') as input_file:
    counts = Counter(word.translate(str.maketrans('', '', string.punctuation)).upper() for line in input_file for word in line.split())

with open('romeo_unique.txt', 'w') as output_file:
  for word in counts:
    output_file.write(word + '\n')

据我从文档中可以看出,默认情况下不保证计数器按出现次数排序;然而:

  • 当我在交互式 python 解释器中使用它们时,它们总是以减少的出现次数打印;
  • 它们提供了一种方法.most_common(),该方法保证在出现次数减少的情况下返回。

推荐阅读