这是我的代码
def getInputFile ():
bad = True
while bad:
try:
fileName = input ("Enter file name: ")
# Open file for input
f = open(fileName, "r") # Note: "r" means open for reading.
bad = False
except Exception as err:
print ("Please enter a valid file name:")
return f
lines=0
wordCount=0
fileHandler=getInputFile()
for lineOfText in fileHandler.readlines():
lines += 1
print(str(lines),str(lineOfText))
f1=lineOfText.split()
wordCount=wordCount+len(f1)
print ("Word count:" +str(wordCount))
目前,我的程序只计算文本文件中运行的单词总数,但我希望它只计算文件每行中的单词。此外,我希望程序能够在最后分析文本文件,并打印出诸如"大多数单词和#34;和"每行平均字数"但是我不能用我目前的格式做到这一点。任何帮助将不胜感激。
答案 0 :(得分:1)
从中创建list
:
result = [len(line.split()) for line in fileHandler]
然后你可以找到总字数:
print(sum(result))
每行的字数:
print(*result, sep='\n')
最高字数:
print(max(result))
平均字数:
print(sum(result) / len(result))
如果您还想保存每一行,请先阅读:
lines = fileHandler.readlines()
然后计算单词:
result = [len(line.split()) for line in lines]
然后zip()
这两个list
s:
print(*('{} -- {}'.format(*item) for item in zip(lines, results)), sep='\n')
答案 1 :(得分:1)
你几乎就在那里,只需添加一些东西:
lines=0
wordCount=0
mostWordsInLine = 0
fileHandler=getInputFile()
for lineOfText in fileHandler.readlines():
lines += 1
print(str(lines),str(lineOfText))
f1=lineOfText.split()
wordCount=wordCount+len(f1)
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
print ("Word count:" +str(wordCount))
print "Average words per line: {}".format(wordCount / lines)
print "Most words in a single line: {}".format(mostWordsInLine)
编辑:要打印出每行中的单词数,您可以更改print
循环中的for
语句。
目前你正在做print ("Word count:" +str(wordCount))
,它打印出累计总数。只需将其更改为print 'Word count: {}'.format(len(f1))