【问题标题】:Python - Counting Words In A Text FilePython - 计算文本文件中的单词
【发布时间】:2014-11-04 20:45:47
【问题描述】:

我是 Python 新手,正在开发一个程序,该程序将计算简单文本文件中单词的实例。程序和文本文件将从命令行读取,因此我在我的编程语法中包含了用于检查命令行参数的内容。代码如下

import sys

count={}

with open(sys.argv[1],'r') as f:
    for line in f:
        for word in line.split():
            if word not in count:
                count[word] = 1
            else:
                count[word] += 1

print(word,count[word])

file.close()

count 是一个字典,用于存储单词和它们出现的次数。我希望能够打印出每个单词及其出现的次数,从出现次数最多到出现次数最少。

我想知道我是否走在正确的轨道上,以及我是否正确使用了 sys。谢谢!!

【问题讨论】:

  • 看起来不错并且相当 Pythonic。不过,处理每行末尾的换行符,最后一个字符将是 '\n' 这会弄乱你的计数。你会想要使用for word in line[:-1].split(): 或其他东西。
  • @Gaz Davidson:line.split() 将清理所有空白。
  • 您可能喜欢使用 re.findall(r'\w+', ...) 将内容分成单词,因为它不仅仅将空格作为分隔符...参见this example from the python docs跨度>

标签: python


【解决方案1】:

你所做的对我来说看起来不错,还可以使用collections.Counter(假设你是 python 2.7 或更高版本)来获取更多信息,比如每个单词的数量。我的解决方案看起来像这样,可能会有一些改进。

import sys
from collections import Counter
lines = open(sys.argv[1], 'r').readlines()
c = Counter()
for line in lines:
    for work in line.strip().split():
        c.update(work)
for ind in c:
    print ind, c[ind]

【讨论】:

    【解决方案2】:

    你最后的print 没有循环,所以它只会打印你读到的最后一个单词的计数,它仍然是word 的值。

    另外,使用with 上下文管理器,您不需要close() 文件句柄。

    最后,正如评论中所指出的,您需要在 split 之前从每个 line 中删除最后一个换行符。

    对于这样一个简单的程序,它可能不值得麻烦,但您可能希望查看Collections 中的defaultdict,以避免在字典中初始化新键的特殊情况。

    【讨论】:

      【解决方案3】:

      我刚刚注意到一个错字:您以f 打开文件,但以file 关闭它。正如tripleee 所说,您不应该关闭在with 语句中打开的文件。此外,将内置函数的名称(如filelist)用作您自己的标识符也是一种不好的做法。有时它可以工作,但有时它会导致令人讨厌的错误。这让阅读您的代码的人感到困惑;语法高亮编辑器可以帮助避免这个小问题。

      要按计数的降序打印count dict 中的数据,您可以执行以下操作:

      items = count.items()
      items.sort(key=lambda (k,v): v, reverse=True)
      print '\n'.join('%s: %d' % (k, v) for k,v in items)
      

      有关 list.sort() 方法和其他方便的 dict 方法的更多详细信息,请参阅 Python 库参考。

      【讨论】:

        【解决方案4】:

        我只是通过使用 re 库来做到这一点的。这是针对文本文件中每行的平均单词数,但您必须找出每行的单词数。

        import re
        #this program get the average number of words per line
        def main():
            try:
                #get name of file
                filename=input('Enter a filename:')
        
                #open the file
                infile=open(filename,'r')
        
                #read file contents
                contents=infile.read()
                line = len(re.findall(r'\n', contents))
                count = len(re.findall(r'\w+', contents))
                average = count // line
        
                #display fie contents
                print(contents)
                print('there is an average of', average, 'words per sentence')
        
                #closse the file
                infile.close()
            except IOError:
                print('An error oocurred when trying to read ')
                print('the file',filename )
        
        #call main
        main()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-07-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-09
          相关资源
          最近更新 更多