按计数排序字典Python

时间:2014-04-18 20:18:57

标签: python sorting dictionary

#!/bin/env/python


import sys
import os

if len(sys.argv) == 3:
  #We know the user typed Script then Filename
  file = sys.argv.pop(2)
  num = sys.argv.pop(1)
  #Establish Vars
  f1 = open(file)
  counts = dict()
  #Open the file and create a dictionary

  for line in f1:
    words = line.split()
    for word in words:
      if word not in counts:
        counts[word] = 1
      else:
        counts[word] += 1
  #print counts
  #Iterate through all words and either establish word = 1 or increment
  #counts = sorted(counts, key=words.get)
  print counts


else:
   print('Can you please use this format [script] [number] [file] ')

我需要让这个程序按字词

在字典中对文件进行排序

我遇到了一个问题,按计数进行排序并不按计数排序,我需要将其排序到最频繁到最不频繁的任何人都能看到问题。它输出的数字被砍掉了?

1 个答案:

答案 0 :(得分:0)

键= counts.get

键= words.get