2014-04-12 67 views
1

我想弄清楚如何使用變量來控制腳本打印的行數。我想使用輸出變量並只打印用戶請求的行數。任何幫助將不勝感激。用於控制打印多少行的變量Python


import sys, os 

print "" 
print "Running Script..." 
print "" 
print "This program analyzes word frequency in a file and" 
print "prints a report on the n most frequent words." 
print "" 

filename = raw_input("File to analyze? ") 
if os.path.isfile(filename): 
    print "The file", filename, "exists!" 
else: 
    print "The file", filename, "doesn't exist!" 
    sys.exit() 
    print "" 
output = raw_input("Output analysis of how many words? ") 

readfile = open(filename, 'r+') 

words = readfile.read().split() 
wordcount = {} 
for word in words: 
    if word in wordcount: 
    wordcount[word] += 1 
    else: 
    wordcount[word] = 1 

sortbyfreq = sorted(wordcount,key=wordcount.get,reverse=True) 
for word in sortbyfreq: 
    print "%-20s %10d" % (word, wordcount[word]) 
+0

你怎麼知道的排序此功能:與

from collections import Counter sortbyfreq = Counter(words) # Instead of the wordcount dictionary + for loop. 

然後,您可以訪問用戶定義最常見的元素? – user3286261

回答

1

只需創建您的最終循環,檢查完成的循環,斷線次數時一定數目已經達到了一個櫃檯。

limit = {enter number} 
counter = 0 
for word in sortbyfreq: 
    print "%-20s %10d" % (word, wordcount[word]) 
    counter += 1 
    if counter >= limit: 
    break 
1

詞典本質上是無序的,所以在按頻率排序後,您不會在任何地方嘗試輸出元素。

使用collections.Counter代替:

n = int(raw_input('How many?: ')) 
for item, count in sortbyfreq.most_common(n): 
    print "%-20s %10d" % (item, count)