python - 输出未排序,无法对第二个值进行排序。是否有特殊方法对第二个值进行排序
问题描述
输出未排序,无法对第二列进行排序。是否有特殊方法对第二个值进行排序。
这个程序接受一个文本并计算一个单词在文本中出现的次数
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)
解决方案
具有默认值的字典
代码片段:
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 的子类Counter
collections
。它将为您完成所有艰苦的工作。
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()
,该方法保证在出现次数减少的情况下返回。
推荐阅读
- solr - 如何将条件或过滤器添加到自动建议的 solr 术语查询
- java - 如何在 Java 中本地触发现有的 AWS lambda?
- css - 如何在 vuetify v2 中更改 scss 中的断点?
- c++ - 如何在 Eigen 中编写以下 Matlab 代码:vec(1:n) = vec(idx)?
- excel - 如果单元格为空,则复制上面的整行并插入到空单元格的行中
- java - 如何创建 ArrayListMultiMap?
- sql - 在 Redshift 中获取视图的“大小”
- php - 方法 Illuminate\Database\Eloquent\Collection::paginate 不存在
- html - 我想让我的网页上的元素堆叠在一起
- python - LinkedIn API get /v2/me 返回“参数中存在未经许可的字段”