【发布时间】:2017-04-24 08:06:33
【问题描述】:
我正在尝试计算文本文件(与此相关的任何文本文件)中的段落数和最常用的单词,但是当我运行我的代码时似乎输出为零,也没有错误。关于我哪里出错的任何提示?
filename = input("enter file name: ")
inf = open(filename, 'r')
#frequent words
wordcount={}
for word in inf.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for key in wordcount.keys():
print ("%s %s " %(key , wordcount[key]))
#Count Paragraph(s)
linecount = 0
for i in inf:
paragraphcount = 0
if '\n' in i:
linecount += 1
if len(i) < 2: paragraphcount *= 0
elif len(i) > 2: paragraphcount = paragraphcount + 1
print('%-4d %4d %s' % (paragraphcount, linecount, i))
inf.close()
【问题讨论】:
-
与其关闭文件,不如考虑使用
with语句在上下文管理器中打开文件。还要确认您要使用的file mode,即r+。使用enumerate(inf.readlines)循环文件中的行;然后,您可以拆分单词并计算每行的行数。最后,使用collections.Counter来计算单词和段落,而不是经典的增量器。这些建议可以让你的代码更加 Pythonic。
标签: python file python-3.x for-loop count