python开发_re和counter

时间:2023-03-09 17:31:18
python开发_re和counter

pythonrecounter的结合,可以实现以下的功能:

1.获取字符串或者文件中的单词组

2.对单词组进行统计

下面是我做的demo

运行效果:

python开发_re和counter

=============================================

代码部分:

=============================================

 #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()