按单词频率对列表进行排序:排序时不输出频率

问题描述 投票:0回答:1

我正在尝试编写一个程序,该程序将输出以字母表中的每个字母开头的单词的出现情况。到目前为止,我已经让代码可以工作并输出正确的数字。然而问题是,当尝试按字母顺序对频率进行排序时,频率也不会输出。我对 python 相当陌生,我不确定如何解决这个问题。

我的代码如下所示:

f = open('textfile.txt','r')
data=f.read()
words= data.split()
#Alphabet occurence
alpha ={}
for alphaword in words:
  key = alphaword[0].upper()
  if key in alpha:
    alpha[key] +=1
  else:
    alpha[key] = 1
sortedalpha=sorted(alpha)
print("The occurence of words beginning with each letter is: ")
print(alpha)
print("")
print(sortedalpha)

这是没有排序的输出(alpha)

{'T': 14, 'S': 4, 'W': 4, 'F': 1, 'R': 2, 'O': 7, 'A': 2, 'L': 2, 'G': 1, 'C': 1, 'D': 2, 'H': 1, 'M': 1, 'P': 2}

这是我尝试对其进行排序时的输出(sortedalpha)

['A', 'C', 'D', 'F', 'G', 'H', 'L', 'M', 'O', 'P', 'R', 'S', 'T', 'W']

然而我想要的是这个

['A': 2, 'C': 1, 'D': 2,'F': 1,'G': 1, 'H': 1, 'L': 2, 'M': 1, 'O': 7, 'P': 2, 'R': 2, 'S': 4, 'T': 14, 'W': 4]

python list sorting frequency-analysis
1个回答
0
投票

因此,当您在字典上调用 sort() 时,Python 只会按照代码中的情况对字典的 keys 进行排序。如果您想根据键对整个字典进行排序,但又想保留它们各自的值,那么您需要将

sortedalpha = sorted(alpha)
替换为
sortedalpha = dict(sorted(alpha.items()))
,就像 Michael Butcher 在您的评论中提到的那样。这是有效的,因为 .items() 返回整个字典的只读迭代,它允许您访问键和值。所以你的代码应该看起来像这样:

f = open('textfile.txt','r')
data=f.read()
words= data.split()
#Alphabet occurence
alpha ={}
for alphaword in words:
  key = alphaword[0].upper()
  if key in alpha:
    alpha[key] +=1
  else:
    alpha[key] = 1
sortedalpha=dict(sorted(alpha.items())) # here is the change
print("The occurence of words beginning with each letter is: ")
print(alpha)
print("")
print(sortedalpha)

如果您想访问字典中所有值的列表,而不需要它们各自的键,那么您可以使用 .values(),对于键,您可以使用 .keys()

© www.soinside.com 2019 - 2024. All rights reserved.