2016-11-21 91 views
0

我寫了一個函數來計算一個單個字母的出現給定的字符串:返回多少次出現在每個字母在字符串

def count_letters(string, letter): 
'''returns the number of letters letter in a sentence string.''' 

count = 0 
for char in string: 
    if char == letter: 
     count += 1 
return count 

現在,我想找到一種方法,返回以列表格式顯示所有字母出現的次數(假設它們都是小寫字母 - 我正在使用string.lower())。我初始化的信計數器26 0的列表:

letter_counter = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 

但我不知道如何遍歷一個給定的字符串和追加列表爲每個字母。

Ex。如果,letter_counter回報:

letter_counter = [0,0,0,0,1,0,0,1,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0] 

我認爲這只是一個爲內循環for循環的問題,但似乎更加複雜。或者我可能只是看了太久。

在此先感謝。

+0

使用'collections.Counter'是序列中出現次數最常用的方法。你也可以在'letter_counter'上做一個for循環,確保將每個索引轉換成帶有'chr(ord('A'+ i))'的字符。 –

回答

1

爲什麼重新發明輪子?

您可以使用collections.Counter(string)這將返回一個字典中字符串中的所有字母作爲關鍵字和頻率作爲所述關鍵字的值。

+0

啊,足夠公平,我主要只是想看看它是否可以用循環:) – maio123maio

1

更好的方法是使用Alessandro Power和Pythonista建議的集合。如果你不想使用黑盒,那麼這就是你可以做的。

# Replace this with your string 
    string = 'AbcdEfghiJ' 
    # create dictionary to locate a position of each letter 
    str_dict = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':6, 'h':7, 
     'i':8, 'j':9, 'k':10, 'l':11, 'm':12, 'n':13, 'o':14, 
     'p':15, 'q':16, 'r':17, 's':18, 't':19, 'u':20, 'v':21, 
     'w':22, 'x':23, 'y':24, 'z':25} 
    letter_counter = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 
    # locate a position of char in letter_counter and add 1. 
    for char in string: 
     str_lower = char.lower() 
     letter_counter[str_dict[str_lower]] += 1 

    print letter_counter 

輸出[1]:[1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0]

+0

非常感謝!你知道我如何用句子做這個工作嗎?當我嘗試用空格(例如「hello goodbye」)做一個句子時,它會返回鍵錯誤:''我試圖使用.strip()和.replace(),但那不起作用。 – maio123maio

+0

@ maio123maio:您應該添加「if char!='':」以確保只計算字母而不是空格。然後,代碼將如下所示: –

+0

....... char:string中的字符: if char!='':#'!='意味着'不等於' str_lower = char.lower( ) letter_counter [str_dict [str_lower]] + = 1 print letter_counter –

0

您可以使用ord()將小寫字符轉換爲基於0的索引並將其減去97('a'= 97'' b'= 98等):

def count_letters(word): 
    l_count = [0] * 26 
    for c in word.lower(): 
     l_count[ord(c)-97] += 1 
    return l_count 

> count_letters('aaabbc') 
[3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 

你應該避免在字符串中循環26次來單獨計算每個字母!

1

要算字母,你有很多選擇,按優先順序:

  1. collections.Counter,如果你想獲得這個快速完成。
  2. 使用字典(這是什麼Counter做什麼)
  3. 使用(零)填充列表 - 您的方法。

的collection.Counter做法很簡單:

>>> from collections import Counter 
>>> Counter('hello').most_common() 
[('l', 2), ('h', 1), ('e', 1), ('o', 1)] 

的字典方法,需要多做一些工作。有兩種方法可以做到這一點。第一種方法是使用字典的方法來確保在第一次看到一封信時,它會使用默認值正確初始化。

>>> d = {} 
>>> for letter in 'hello': 
... d[letter] = d.setdefault(letter, 0) + 1 
... 
>>> d 
{'h': 1, 'e': 1, 'l': 2, 'o': 1} 

第二種方法使用相同的概念與上述相似,但採用defaultdict代替:

>>> from collections import defaultdict 
>>> d = defaultdict(int) 
>>> for letter in 'hello': 
... d[letter] += 1 
... 
>>> d 
defaultdict(<type 'int'>, {'h': 1, 'e': 1, 'l': 2, 'o': 1}) 

甲defaultdict是一個對象,需要一個可調用的(函數),它的值將是如果字典中不存在密鑰,則將其指定爲默認值。與setdefault相同,但它可以做的更靈活一些。

的最後一個選項是零填充列表:

>>> counts = [0 for i in range(25)] 
>>> for letter in 'hello': 
...  counts[ord(letter.lower()) % 97] += 1 
... 
>>> counts 
[0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 
>>> counts[11] 
2 

有這種方法的幾個問題;最大的一個是,它只能使用特定的詞作品,它不會與短語,如hello world或那些串連,或標點符號的話工作:We've won!

您可以圍繞這些經常方案,但其他方法不要沒有這些問題。

相關問題