python开发_re和counter
2013-08-15 00:33
183 查看
python中re和counter的结合,可以实现以下的功能:
1.获取字符串或者文件中的单词组
2.对单词组进行统计
下面是我做的demo
运行效果:
=============================================
代码部分:
=============================================
1.获取字符串或者文件中的单词组
2.对单词组进行统计
下面是我做的demo
运行效果:
=============================================
代码部分:
=============================================
#python re and counter object ''' 读取一个文件,获取到该文件中的所有单词组,然后对该单词组进行个数统计,也可以根据 条件统计,如:该单词组中出现最多的前number个单词 ''' import os import re from collections import Counter def get_words(path): '''读取一个文件中的内容,返回该文件中的所有单词''' if os.path.exists(path): return re.findall(r'\w+', open(path).read().lower()) else: print('the path [{}] is not exist!'.format(path)) def get_most_common_words(words, number): ''' 如果<code>number > 0</code>,则返回该单词组中出现最多的前<code>number</code>个单词 否则,返回该单词组中所有统计情况 ''' if number > 0: return Counter(words).most_common(number) else: return Counter(words) def main(): temp_path = 'c:\\temp.txt' number = 5 words = get_words(temp_path) print(words) print('#' * 50) cnt = get_most_common_words(words, -1) print(cnt) print('#' * 50) cnt = get_most_common_words(words, number) print(cnt) if __name__ == '__main__': main()
相关文章推荐
- Python开发——re.sub
- 【Python开发】Python之re模块 —— 正则表达式操作
- python全栈开发-re模块(正则表达式)应用(字符串的处理)
- Python开发【模块】:re正则
- python开发_counter()
- python3 开发面试题(collections中的Counter)6.7
- Python模块:Re模块、附软件开发目录规范
- python开发_counter()
- Python开发【第一篇】:初识Python
- Python开发利器spyder
- python中使用re.sub更换倒数第一个字符串
- HTM层级实时记忆开发平台Nupic安装方法(pYTHON VERSION)
- Python中使用Counter进行字典创建以及key数量统计
- 正则表达式Reguler Expression (with python re)
- python开发_logging_日志处理
- Python开发中的一些小的tips记录
- Python re(正则表达式)简明教程
- webpy 使用python3开发
- Python的开发插件PyDev在Eclipse下的安装过程(解决mylyn的问题in Windows)
- Python 图形界面开发环境搭建(Python2.7 + pyQT4 + Eric4)