zoukankan      html  css  js  c++  java
  • python开发_re和counter

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

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

    2.对单词组进行统计

    下面是我做的demo

    运行效果:

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

    代码部分:

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

     1 #python re and counter object
     2 '''
     3 读取一个文件,获取到该文件中的所有单词组,然后对该单词组进行个数统计,也可以根据
     4 条件统计,如:该单词组中出现最多的前number个单词
     5 '''
     6 import os
     7 import re
     8 from collections import Counter
     9 
    10 def get_words(path):
    11     '''读取一个文件中的内容,返回该文件中的所有单词'''
    12     if os.path.exists(path):
    13         return re.findall(r'w+', open(path).read().lower())
    14     else:
    15         print('the path [{}] is not exist!'.format(path))
    16 
    17 def get_most_common_words(words, number):
    18     '''
    19     如果<code>number > 0</code>,则返回该单词组中出现最多的前<code>number</code>个单词
    20     否则,返回该单词组中所有统计情况
    21     '''
    22     if number > 0:
    23         return Counter(words).most_common(number)
    24     else:
    25         return Counter(words)
    26     
    27 def main():
    28     temp_path = 'c:\temp.txt'
    29     number = 5
    30     words = get_words(temp_path)
    31     print(words)
    32     print('#' * 50)
    33     cnt = get_most_common_words(words, -1)
    34     print(cnt)
    35     print('#' * 50)
    36     cnt = get_most_common_words(words, number)
    37     print(cnt)
    38 
    39 if __name__ == '__main__':
    40     main()
  • 相关阅读:
    过采样算法之SMOTE
    4.4 spring-自定义标签的解析
    4.3 spring-嵌入式beans标签的解析
    4.2 spring-import 标签的解析;
    4.1 spring-alias 标签的解析;
    4.0 spring-注册解析的Bean
    3.9 spring-自定义标签解析
    3.8 spring
    3.8 spring-qualifier 子元素的使用与解析
    3.7 spring-property 子元素的使用与解析
  • 原文地址:https://www.cnblogs.com/hongten/p/hongten_python_counter_and_re.html
Copyright © 2011-2022 走看看