通過python實現字頻統計

字頻統計

字頻統計1

如果碰見了這類題目, 妥妥的字頻統計.一種是直接百度找相關的字頻統計網站, 一種是自己動手寫腳本練練自己的編程能力.

此處有一大串英文, 統計每個詞出現的頻率.

hello python, i am a baby, i want to a hacker.

一般的腳本寫法:

#!/usr/bin/python3
# -*- coding=utf8 -*-
"""
# @Author : pig
# @CreatedTime:2020-02-27 16:51:52
# @Description : 
"""

my_str = "hello python, i am a baby, i want to be a hacker."

def str_count(strs):
	'''利用字典中的get方法, 如果存在加1, 如果字母不存在返回0'''
	str_dict = {}
	for i in strs:
		str_dict[i] = str_dict.get(i,0) + 1
	return str_dict


count = str_count(my_str)
print (count)

結果:

{'a': 6, 'b': 3, 'w': 1, 'i': 2, 'p': 1, 't': 3, 'h': 3, 'c': 1, '.': 1, 'n': 2, 'y': 2, 'o': 3, 'e': 3, 'k': 1, ',': 2, 'l': 2, 'm': 1, 'r': 1, ' ': 11}

利用collection模塊簡化代碼

使用collection中的counter計數方法

from collections import Counter

my_str = "hello python, i am a baby, i want to be a hacker"
print (Counter(my_str))

Counter({' ': 11, 'a': 6, 'h': 3, 'o': 3, 'b': 3, 't': 3, 'e': 3, 'n': 2, 'l': 2, ',': 2, 'i': 2, 'y': 2, 'c': 1, 'm': 1, 'k': 1, 'r': 1, 'w': 1, 'p': 1})

實例

8dct^oKndKFz*~IhtJ5(Pu*H}J)Z?m2~-`~.Rg=s2m^*=r,?zX1WfLm_;gx.f4RFdHkDl SZ`KRk#Mfxr~VoAZwY(%9&P]AX)5Uzt+k.%?G  3HS+L71I$)i4[K-H`+dG`99txSKmUMv+Avd]bF99wN1z[HSo-lf|Fs.heF+%reA7:;(S`?&f2i)]vTo,/i,yHdIy)MKoN.n`.RqT2M}?3AipjjquK7rL]+8$yauVJzn2(a;,B~B@Y9c[j;ic1o2*UU8zHnc.,q3jb~v%|Z :|C;^mm/qiV,ED2KQGm&h{zZj,%8,N~Ns{;YwcKt|^3p.cNN!GhJ8U{-eBIz/,#o^/hRe.@$GC+x}@I4;a^D%E/{z_Q:GMPBV$Q8DMVN5CvF62)=vYv3k:[gZqBk.wjvrHZ]$}8-Mg}@L|~uSP;tO~CrVl1qqFP/?lkSHA;fT,wV/ -wPtkn*t]|!-Fvp1bFgF{u|^fC=H*FECiNO3di3b?z8zFQ;s?L&ycA=(z8]DYhp^$JK,NG1y.7j@` Y;w|W4#!rRr$IsT$(M,oO m s&DNyk#JZ/!bb;rbbSgq#8COg+501x`ckCJ-D11BmE6KI^~LIZ+79VwGJ;f%`f~`cEL,/|59dir^U*a2`UK%gP,vcAO{=]orW:(EvGq`%Y&?eI,.Gv#M4J(Kh0(d@&5qP4y/KI{Z]}0/x?v:W]N*JLN@DNn!`@~Svr:rO=.dQz]K_3Vz+9Xf-[Qq2D*lB*zOv?G4iCR6&lZs1A#|=F */n*|Aw[@2{W7]5%`Yh|#y:^$J7F!~jgz7SkJ[VR$psNGHj&!^O.=7,-|:`1TcpJr6dMB86SkKkYDKv;NnIWI,IJ$0h@nP2]Xh/E~hi_qc*5Tz14;#^ 47x6z#A1/Z}U%D&9{Zw#^Xb=YLMqSFBQ4?U@C)X&_3Sx2xS4OFq-89?!e3#&S&=y|,!ImN,vuuT!1PO/M|vf1]|fVLyF;|vL !4JkT4ed!5XrY2n1UEnP4m2StA.^nJy=O7p,U]+rRF,.&ew|
from collections import Counter

with open("字符統計2.txt") as f:
	text_list = f.readlines()
	'''將讀取的內容轉換爲字符串'''
	text_str = ''.join(text_list)
	count = Counter(text_str)
	print (count)

Counter({',': 21, 'v': 19, 'F': 18, 'z': 18, '|': 18, 'K': 17, '1': 17, 'J': 16, 'N': 16, 'S': 16, 'r': 16, ';': 16, '.': 16, '/': 15, ']': 15, '2': 15, '^': 15, '`': 15, 'q': 14, 'I': 14, '~': 14, '&': 14, '4': 14, '*': 13, '?': 13, 'Z': 13, 'k': 13, '!': 12, 'G': 12, 'd': 12, 'A': 12, '8': 12, 'f': 12, 'M': 12, 'n': 12, 'c': 12, '=': 12, '#': 12, '+': 11, 'V': 11, '%': 11, 'y': 11, 'L': 11, '-': 11, 'P': 11, '@': 11, 'w': 11, 'i': 11, ' ': 11, '9': 11, 'D': 11, 'U': 11, 'O': 11, '7': 11, 'h': 11, '$': 11, 'Y': 11, 'm': 11, 'H': 11, 'C': 10, '3': 10, '{': 9, 'j': 9, 'b': 9, 'R': 9, 'x': 9, ':': 9, 't': 9, 'o': 9, 'B': 9, '5': 9, '(': 9, 'g': 9, 's': 8, 'e': 8, 'E': 8, 'T': 8, '}': 7, '[': 7, 'p': 7, 'Q': 7, 'u': 7, ')': 7, 'X': 7, 'l': 6, '6': 6, 'W': 6, '_': 5, 'a': 4, '0': 4})

這下多少個w都有了.

得到的參數通過post提交得到flag

from collections import Counter

with open("字符統計2.txt") as f:
	text_list = f.readlines()
	'''將讀取的內容轉換爲字符串'''
	text_str = ''.join(text_list)
	count = Counter(text_str)
	value = '%d'%count['w'] + '%d'%count['o'] + '%d'%count['l'] + '%d'%count['d'] + 
'%d'%count['y']
	print ('要提交的參數爲', value)
	
要提交的參數爲 11961211

可以使用most_common(10) 來提取最高的前10字符(在這裏沒有這個必要)

counter

collections是一個容器模塊, 來提供python標準內建容器dict, list, set, tuple的替代選擇, 也就是說collections是python內建容器的補充.

counter是字典的子類, 用於計算可哈希對象, 計數元素想字典鍵一樣存儲. 可以使用字典的所有方法

創建counter對象

from collection import Counter
c = Counter()
c = Counter("adfasfsfa") # 用迭代對象創建一個counter對象
c = Counter({'red':4, "blue":2})
c = Counter(cats=4, dogs=8)

迭代對象計數

from collections import Counter
c = Counter("llll")
print (c)

根據鍵引用值

from collections import Counter
c = Counter('aaaaaa')
c['a']
如果不存在該鍵, 則返回0

刪除其中一個鍵值對

from collections import Counter
c = Counter('baaaa')
del c['a']
print (c)

用映射來創建一個Counter, 並返回迭代器

from collections import Counter
c = Counter({'red':3, 'blue': 1, 'black':2})
list(c.elements())
# 輸出:['red', 'red', 'red', 'blue', 'black', 'black']

查看出現頻率最高的前n元素

from collections import Counter
c = Counter('adafdgadksjdh')
c.most_common(3)

兩個Counter相減

from collections import Counter
c = Counter(a=4, b=2, c=0)
d = Counter(a=1, b=2, c=3)
c.subtract(d)
c

轉換成字典

from collections import Counter
c = Counter('dafasfsa')
dict(c)

添加迭代對象

c.update("aaaa")

Counter 是字典的一個子類,繼承了字典的所有方法.

簡書博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章