gpt4 book ai didi

python - 控制 Python 打印行数的变量

转载 作者:行者123 更新时间:2023-12-01 05:16:48 25 4
gpt4 key购买 nike

我试图弄清楚如何使用变量来控制脚本打印的行数。我想使用输出变量并仅打印用户请求的行数。任何帮助将不胜感激。

<小时/>
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])

最佳答案

只需在最终循环中创建一个计数器,它会检查已完成的循环数量,并在达到特定数量时中断。

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

关于python - 控制 Python 打印行数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com