Python计算某些字符

时间:2013-09-27 13:50:09

标签: python recursion character

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()

我试图计算一定的性格,例如,如果我要把#34; W"在char输入提示符中,它应该只计数W.我该怎么做?我试图在def字符串函数中进行递归

谢谢。

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

我建议您将文件或任何字符串作为字符串变量,然后在字符串的单个元素上使用for循环,并将每个char与读入的char进行比较,并计算+ = 1。 / p>

答案 3 :(得分:0)

如何使用正则表达式模块?

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

我想给你你想要的东西。我尽可能避免递归 - 调试的噩梦!

答案 4 :(得分:0)

使用内置计数功能:

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

3
相关问题