Python - 统计文本文件中的单词数量

3 投票
4 回答
5172 浏览
提问于 2025-04-21 00:30

我刚开始学习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模块。谢谢!!

4 个回答

0

我刚刚用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()
0

我刚注意到一个拼写错误:你打开文件时用的是 f,但关闭时却用 file。正如tripleee所说,你在 with 语句中打开的文件不应该手动关闭。此外,使用内置函数的名字,比如 filelist,来命名你自己的变量是不好的做法。有时候这样做可以运行,但有时候会导致很麻烦的错误。而且,这样会让阅读你代码的人感到困惑;使用语法高亮的编辑器可以帮助避免这个小问题。

如果你想按计数的降序打印你的 count 字典中的数据,可以这样做:

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() 方法和其他实用的字典方法,可以查看 Python 库参考文档。

0

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

另外,使用 with 上下文管理器时,你不需要手动去 close() 文件句柄。

最后,正如评论中提到的,你需要在 split 之前去掉每一行末尾的换行符。

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

3

你做的看起来没问题。其实你也可以用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]

撰写回答