2013-09-27 85 views
0
def file(char, filename): 
    for currentFile in filename: 
     print(currentFile.strip()) 

def string(char, str): 
    count = 0 
    if char in 'abcdefghijklmnopqrstuvwxyz': 
     count += 1 
     string(char,str) 
    else: 
     print("Incorrect Letters") 
    print(count) 

def main(): 
    char = input("Enter character: ") 
    openFile = input("Enter the filename: ") 

    filename = open(openFile) 

    file(char, filename) 
    string(char, str) 

main() 

我想要計算某些字符,例如,如果我要在字符輸入提示中放入「W」,它應該只計算W.我該怎麼做?我正在嘗試在def字符串函數中執行遞歸蟒蛇計數某些字符

謝謝。

+3

看一看這個http://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-python -string –

+4

'file'和'string'已經存在於python中,所以不要把它們當作我thod的名字。 –

+0

由於你沒有變量'str',這行:'string(char,str)'不起作用。 –

回答

1

這個問題很容易/更有效的使用循環來解決,但如果你真的想編寫一個遞歸解決方案,讓我們來看看如何做到這一點。第一個例子,如何計算字符串中的小寫字母數(這是正確的執行你的string()功能):

import string 

def countString(strg): 
    if not strg:        # if it's the empty string 
     return 0        # then it has 0 letters 
    elif strg[0] in string.ascii_lowercase: # if the first char is a letter 
     return 1 + countString(strg[1:])  # add 1 and continue with recursion 
    else:         # if the first char is not a letter 
     raise Exception, 'Incorrect Letters' # then throw an exception 

countString('abcd') 
=> 4 

countString('ab$cd') 
=> Exception: Incorrect Letters 

以上將返回小寫字母數輸入字符串,或如果找到非字母字符,則會拋出異常。注意,如果出現非字母字符,則不能只打印消息,還必須停止遞歸 - 這就是爲什麼我要引發異常。

第二個例子,如何計算字符串中的字符出現的次數(這回答標題中的問題),它類似於前面的例子,但它只能算作參數傳遞的字符:

def countChar(strg, ch): 
    if not strg:       # if it's the empty string 
     return 0       # then ch's count is 0 
    elif strg[0] == ch:     # if the first char is ch 
     return 1 + countChar(strg[1:], ch) # add 1 and continue with recursion 
    else:         # if the first char is not ch 
     return countChar(strg[1:], ch)  # simply continue with recursion 

countChar('abcdeabca', 'a') 
=> 3 

countChar('abcdeabca', 'x') 
=> 0 
0

我建議你將文件或任何字符串作爲字符串變量,然後對字符串的單個元素使用for-loop並將每個字符與char讀入並計數+ = 1進行比較。

0

如何使用正則表達式模塊?

import re 
len(re.findall('W','fasrWfdsfWfsW')) 

我想給你你想要的。儘可能避免遞歸 - 調試的噩夢!

1

這是一個沒有遞歸和正則表達式的解決方案,只是使用內置插件。

import sys 

char = raw_input("Enter character: ") 
# 'isalpha' does the same as your manual check and is more idiomatic 
if not char.isalpha(): 
    print "Incorrect letters" 
    # This will terminate the script 
    sys.exit() 


fname = raw_input("Enter filename: ") 

count = 0 

# We use a context manager to open a file, this way we don't 
# have to close it ourselves when we're done. This is the idiomatic 
# way to open files in Python since context managers were introduced. 
with open(fname, 'r') as fp: 
    # We go through the file line by line 
    for line in fp: 
     # We can use the built-in 'count' method to count 
     # the occurences of a character in a string 
     # Use 'line.lower().count(char)' if you want to be case-insensitive 
     count += line.count(char) 

print count 
+0

in」with open(fname,' r')作爲fp ..「什麼是'r'? – Singh2013

+0

-1,因爲雖然是正確的,但它不符合向OP解釋遞歸概念的要求,以便他可以完成他的任務。 –

0

使用內置計數功能:

l = 'abcdeabca' 
l.count('a') 

3