Python统计文本文件字数与词频的完整实现
本文介绍使用Python统计文本文件字数及词频的方法。通过读取file.txt,预处理标点符号并转换为小写,利用字典统计单词出现次数。代码包含按频率排序及输出Top N单词的功能,适合Python初学者参考文件处理与基础算法实现。
本文详细介绍利用Python语言统计文本文件字数的具体实现方案,旨在为读者提供实用的代码参考。
程序的主要功能是从当前运行目录下的file.txt文件中读取内容,并对其进行字数统计处理。
# -*- coding: GBK -*-
import string
import sys
reload(sys)
def compareItems((w1,c1), (w2,c2)):
if c1 > c2:
return - 1
elif c1 == c2:
return cmp(w1, w2)
else:
return 1
def main():
fname = "file.txt"
try:
text = open(fname,'r').read()
text = string.lower(text)
except:
print "\nfile.txt is not exist!!! or There is a R/W error! "
sys.exit()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
text = string.replace(text, ch, ' ')
words = string.split(text)
counts = {}
for w in words:
counts[w] = counts.get(w,0) + 1
n = input("\n输入要统计的top单词数:")
items = counts.items()
items.sort(compareItems)
max = len(items)
print "\n单词总计:" + str(len(words))
print "单词净个数(已去重):" + str(max)
print "\n"
if n > max:
n = max
for i in range(n):
print "%-10s%5d" % items[i]
if __name__ == '__main__':
main()
此外,本文还推荐两款实用的在线统计工具,供读者在实际工作中辅助使用:
在线字数统计工具: http://tools.jb51.net/code/zishutongji
在线字符统计与编辑工具: http://tools.jb51.net/code/char_tongji
如需深入了解Python相关技术,建议查阅本站系列教程,包括《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》以及《Python入门与进阶经典教程》。
以上内容希望对各位Python程序开发者有所助益。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













