如何用Python实现任一个英文的纯文本文件,统计其中的单词出现的个数?
2015-10-12 20:44
1011 查看
import re file_name = 'test.txt' lines_count = 0 words_count = 0 chars_count = 0 words_dict = {} lines_list = [] with open(file_name, 'r') as f: for line in f: lines_count = lines_count + 1 chars_count = chars_count + len(line) match = re.findall(r'[^a-zA-Z0-9]+', line) for i in match: # 只要英文单词,删掉其他字符 line = line.replace(i, ' ') lines_list = line.split() for i in lines_list: if i not in words_dict: words_dict[i] = 1 else: words_dict[i] = words_dict[i] + 1 print 'words_count is', len(words_dict) print 'lines_count is', lines_count print 'chars_count is', chars_count for k,v in words_dict.items(): print k,v
相关文章推荐
- python编码问题初探
- LeetCode----Add Digits
- python遗产
- Python import module 的几种情况
- 使用python统计出txt文档中含有某个单词的个数
- LeetCode----Combinations
- 写一个python程序调用windows下django开发服务器
- Python 获取新浪财经数据的案例
- Python tkinter调整元件在窗口中的位置与几何布局管理
- Python语法快速入门指南
- 初步认识Python中的列表与位运算符
- Python入门学习之字符串与比较运算符
- Python核心编程第二章习题
- Python.turtle
- python爬虫
- 排序算法总结以及python代码实现
- python发送邮件
- python学习:编码中遇到的问题原因及解决方案
- python 局部local和全局global变量
- python 异常处理