2016-10-04 68 views
0

我正在嘗試僅對來自文本文件的字母進行計數。我想排除任何標點符號和空格。這是迄今爲止我所擁有的。我一直在尋找方法來做到這一點,但每當我嘗試排除某些字符時,我都會收到錯誤。任何幫助是極大的讚賞。Python從文本文件中創建字母數量

#Read Text Files To Memory 
with open("encryptedA.txt") as A: 
    AText = A.read() 
with open("encryptedB.txt") as B: 
    BText = B.read() 

#Create Dictionary Object 
from collections import Counter 
CountA = Counter(AText) 
print(CountA) 
CountB = Counter(BText) 
print(CountB) 
+1

也許你想'計數器(在AText下c如果c.isalnum())' –

回答

0

你是在正確的軌道上,但你想(使用isalnum())來過濾基於字符是字母文本文件(使用isalpha())或字母數字:

from collections import Counter 
with open('data.txt') as f: 
    print (Counter(c for c in f.read() if c.isalpha())) # or c.isalnum() 

對於我的樣本文件中,這個打印:

Counter({'t': 3, 'o': 3, 'r': 3, 'y': 2, 's': 2, 'h': 2, 'p': 2, 'a': 2, 'g': 1, 'G': 1, 'H': 1, 'i': 1, 'e': 1, 'M': 1, 'S': 1}) 
+0

@dawg那是不行的,至少在Python 3.您需要做的'c在線爲c線 – brianpck