2013-08-27 177 views
13

這是我的解決方案導致錯誤。返回0如何計算沒有空格的字符串中的字母數?

PS:我仍然希望修復我的代碼:)

from collections import Counter 
import string 


def count_letters(word): 
    global count 
    wordsList = string.split(word) 
    count = Counter() 
    for words in wordsList: 
     for letters in set(words): 
      return count[letters] 

word = "The grey old fox is an idiot" 
print count_letters(word) 
+1

有什麼錯誤? –

+0

錯誤在於它返回0 –

+6

'len(word.replace(「」,「」))' – Blorgbeard

回答

20
def count_letters(word): 
    return len(word) - word.count(' ') 

或者,如果你有多個字母忽略,你可以過濾字符串:

def count_letters(word): 
    BAD_LETTERS = " " 
    return len([letter for letter in word if letter not in BAD_LETTERS]) 
+0

謝謝馬特。你能告訴我在Python Docs中對word.count的解釋嗎? –

+1

http://docs.python.org/2/library/stdtypes.html#string-methods –

+0

感謝馬特,它不談論這個''的用法。你能否告訴我們它是如何工作的,以及我們可以用它做些什麼。 –

6

MattBryant的答案是一個很好的答案,但是如果你想排除更多類型的字母而不是空格,它會變得笨重。下面是使用Counter當前的代碼的變化,將工作:

from collections import Counter 
import string 

def count_letters(word, valid_letters=string.ascii_letters): 
    count = Counter(word) # this counts all the letters, including invalid ones 
    return sum(count[letter] for letter in valid_letters) # add up valid letters 

輸出示例:

>>> count_letters("The grey old fox is an idiot.") # the period will be ignored 
22 
+0

如果用BAD_LETTERS = [「」,「。」]替換BAD_LETTERS =「」,則其代碼將與您的代碼一樣工作。 –

+1

@AnonymousPi:接受的答案在我上升三分鐘後編輯。當我寫這個答案的時候,只有'len(word) - word.count(「」)'部分在那裏,這是我認爲會延長的尷尬。排除多種字符的簡單擴展,'len(word) - sum(BAD_LETTERS中的字母word.count(字母))'將會非常緩慢(這就是MattBryant沒有提示它的原因!)。 – Blckknght

+0

只是想告訴你...... –

10

使用sum功能簡單的解決方案:

sum(c != ' ' for c in word) 

這是一個記憶有效的解決方案,因爲它使用generator而不是創建臨時列表,然後計算它的總和。

值得一提的是c != ' '回報True or False,這是bool類型的值,但boolint一個亞型,這樣你就可以總結布爾值(True相當於1False對應於0

可以使用mro方法檢查的inheretance:

>>> bool.mro() # Method Resolution Order 
[<type 'bool'>, <type 'int'>, <type 'object'>] 

這裏可以看到,boolint的子類型,它是object的子類型。

+2

這裏值得指出的是,當在數值上下文中使用時,「True」和「False」的行爲與整數「1」和「0」相同。這並不明顯。 – Paolo

+0

@Guandalino好點,我剛剛編輯了答案。 – pkacprzak

3

OK,如果這就是你想要的東西,這是我會做什麼來解決現有的代碼:

from collections import Counter 

def count_letters(words): 
    counter = Counter() 
    for word in words.split(): 
     counter.update(word) 
    return sum(counter.itervalues()) 

words = "The grey old fox is an idiot" 
print count_letters(words) # 22 

如果你不想指望某些非空格字符,那麼你就需要刪除它們 - 在for循環內,如果不早的話。

3

對於另外一個班輪解決方案:

def count_letters(word): return len(filter(lambda x: x not in " ", word)) 

這是通過使用過濾功能,它可以讓你挑傳給你作爲傳遞一個布爾值函數時返回true列表的元素第一個參數。我正在使用lambda函數爲此目的創建一個快速的一次性函數。

>>> count_letters("This is a test") 
11 

您可以輕鬆地擴展這個排除你喜歡的任何字符選擇:

def count_letters(word, exclude): return len(filter(lambda x: x not in exclude, word)) 

>>> count_letters ("This is a test", "aeiou ") 
7 

編輯:但是,你希望得到自己的代碼來工作,所以這裏有一些想法。第一個問題是你沒有設置Counter對象的列表來計數。但是,由於您正在查找字母的總數,因此您需要再次將單詞連接在一起,而不是單獨計算每個單詞。循環添加每個字母的數量並不是必須的,因爲您可以提取值的列表並使用「sum」來添加它們。

這裏有一個版本,這是接近你的代碼,因爲我可以做到,沒有循環:

from collections import Counter 
import string 

def count_letters(word): 
    wordsList = string.split(word) 
    count = Counter("".join(wordsList)) 
    return sum(dict(count).values()) 

word = "The grey old fox is an idiot" 
print count_letters(word) 

編輯:在回答評論問爲什麼不使用一個for循環,這是因爲它不是必要的,並且在許多情況下,使用許多隱含的方式在Python中執行重複性任務可能會更快,更易於閱讀和更高的內存效率。

例如,我可以寫

joined_words = [] 
for curr_word in wordsList: 
    joined_words.extend(curr_word) 
count = Counter(joined_words) 

,但這樣做我拉閘分配額外的陣列,並通過Python解釋我的解決方案執行循環:

count = Counter("".join(wordsList)) 

將執行在大量優化的,編譯的C代碼中。我的解決方案不是簡化該循環的唯一方法,但它是一種方法。

+0

很高興看到你不使用循環,但爲什麼? –

+0

不使用循環的主要原因是沒有必要。 Python提供了許多隱式執行重複任務的方法,而且這些技術通常更快。我會編輯我的答案來解釋一下。 –

2

我設法把它凝結成兩行代碼:

string = input("Enter your string\n") 
print(len(string) - string.count(" ")) 
0

,我發現這是可以正常使用

str = "count a character occurance" 
str = str.replace(' ', '') 
print (str) 
print (len(str)) 
2

使用正則表達式計數字符串中的字母數。

import re 
s = 'The grey old fox is an idiot' 
count = len(re.findall('[a-zA-Z]',s)) 
0
def count_letter(string): 
    count = 0 
    for i in range(len(string)): 
     if string[i].isalpha(): 
      count += 1 
    return count 


print(count_letter('The grey old fox is an idiot.')) 
-3

嘗試使用...

resp = input("Hello, I am stuck in doors! What is the weather outside?") 
print("You answered in", resp.ascii_letters, "letters!") 

並沒有爲我工作,但應該對一些隨機的傢伙工作。

+0

這不起作用。 'resp'對象將沒有'ascii_letters'屬性。更重要的是,不回答被問及的問題 – RandomGuy

0
n=str(input("Enter word: ").replace(" ","")) 

ans=0 
for i in n: 
    ans=ans+1 
print(ans)  
0
word_display = "" 
for letter in word: 
    if letter in known: 
     word_display = "%s%s " % (word_display, letter) 
    else: 
     word_display = "%s_ " % word_display 
return word_display 
+0

僅限代碼解答。請描述這是如何工作的和/或與OP問題有什麼不同。 – lit

相關問題