python開發_counter()


python的API中,提到了Counter,它具有統計的功能

下面是我做的demo:

1.統計自定義字符串中每個字符出現的次數

2.讀取一個文件,把文件中的內容轉化為字符串,統計該字符串中每個字符串出現的次數

運行效果:

測試的文件:

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

代碼部分:

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

 1 #python counter object
 2 
 3 from collections import *
 4 import os
 5 
 6 def get_counter():
 7     '''get the Counter object'''
 8     return Counter()
 9 
10 def str_to_list(s):
11     '''
12     a string covert to list,
13     return an empty list if the string equal None
14     '''
15     if s != None:
16         return [x for x in s]
17     else:
18         return []
19 
20 def counter(c, l):
21     '''統計列表l中每個單詞的出現次數,最后返回一個Counter對象'''
22     for word in l:
23         c[word] += 1
24     return c
25 
26 def get_file_str(path):
27     '''打開指定的文件,並且把文件中的內容以字符串的形式返回'''
28     if os.path.exists(path):
29         temp_str = ''
30         with open(path, 'r') as pf:
31             for line in pf:
32                 temp_str += line
33             return temp_str
34     else:
35         print('the file [{}] is not exist!'.format(path))
36 
37 def test_str():
38     #使用自定義字符串測試
39     #統計自定義字符串中每個字符出現的次數
40     cnt = get_counter()
41     temp_str = 'hello,i\'m Hongten,welcome to my space!'
42     temp_list = str_to_list(temp_str)
43     cnt = counter(cnt, temp_list)
44     print(cnt)
45 
46 def test_file():
47     '''
48     讀取一個文件,把文件中的內容轉化為字符串
49     統計該字符串中每個字符串出現的次數
50     '''
51     cnt = get_counter()
52     temp_path = 'c:\\temp.txt'
53     temp_str = get_file_str(temp_path)
54     temp_list = str_to_list(temp_str)
55     cnt = counter(cnt, temp_list)
56     print(cnt)
57     
58 def main():
59     test_str()
60     print('#' * 50)
61     test_file()
62 
63 if __name__ == '__main__':
64     main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM