2016-05-08 64 views
-2

使用正則表達式,我想要計算具體的字母。我製作了一個如下所示的匹配對象。但不知道如何計算其頻率。大多數計數的例子都是用於單詞,所以我找不到它的好參考。如何匹配特定字母並計算其頻率?

f = open("C:\Python27\test.txt") 
raw_sentence = f.read 
upper_sentence = raw_sentence.upper() 
match = re.findall(r"A", upper_sentence) 

我應該像其他字數統計代碼一樣做一些列表數據嗎?

+0

標題是關於文字和描述是關於字,其中之一是它?有示例輸入和預期輸出也會有幫助。 – niemmi

+0

對不起,這是信。和我想要的結果是像這樣的「A:3」,「B:6」這樣的 –

+0

可能從昨天覆制:[如何可以通過使用python代碼獲得直方圖數對?](http://stackoverflow.com /問題/ 37084670 /何燦I-得到直方圖數與 - 對按使用的Python代碼/) – John1024

回答

1

只需使用str.count

raw_sentence.upper().count('A') 

如果你想多個元素的計數,它能夠更好地使用collections.Counter

>>> s = 'abcabcsdab' 
>>> import collections 
>>> collections.Counter(s) 
Counter({'a': 3, 'b': 3, 'c': 2, 'd': 1, 's': 1})