【问题标题】:Counting Paragraph and Most Frequent Words in Python Text File计算 Python 文本文件中的段落和最常用词
【发布时间】: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


【解决方案1】:
filename = raw_input("enter file name: ")

wordcount={}
paragraphcount = 0
linecount = 0
with open(filename, 'r') as ftext:

    for line in ftext.readlines():
        if line in ('\n', '\r\n'):
            if linecount == 0:
                paragraphcount = paragraphcount + 1
            linecount = linecount + 1
        else:
            linecount = 0
            #frequent words
            for word in line.split():
                wordcount[word] = wordcount.get(word,0) + 1




print wordcount
print paragraphcount

【讨论】:

  • 您可以使用defaultfdict,而不是常规的wordcount dict,例如wordcount = collections.defaultdict(int) --> wordcount[word] += 1.
【解决方案2】:

当您读取文件时,会有一个光标指示您当前正在读取的字节。在您的代码中,您尝试读取文件两次并遇到了一个奇怪的行为,这应该暗示您做错了什么。对于解决方案,

正确的方法是什么?

您应该读取文件一次,存储每一行​​,然后使用同一个存储找到字数和段落数。而不是试图读两遍。

当前代码发生了什么?

当你第一次读取文件时,你的字节光标被设置到文件的末尾,当你尝试读取行时,如果它返回一个空列表,因为它试图读取文件的末尾。您可以通过重置文件指针(光标)来纠正此问题。

在您尝试阅读行之前致电inf.seek(0)。但是,您应该专注于实现我在第一部分中提到的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多