您的位置:首页 > 编程语言 > Python开发

python开发_re和counter

2013-08-15 00:33 183 查看
pythonrecounter的结合,可以实现以下的功能:

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: