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 字符串函数中进行递归

谢谢你。

4

5 回答 5

1

使用内置计数功能:

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

3
于 2013-09-27T15:43:54.440 回答
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
于 2013-09-27T14:12:44.647 回答
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
于 2013-09-27T14:25:20.530 回答
0

How about using regular expressions module?

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

I think gives you what you want. I avoid recursion where possible - nightmare for debug!

于 2013-09-27T14:08:48.050 回答
0

我建议您将文件或任何字符串作为字符串变量,然后对字符串的单个元素进行 for 循环,并将每个字符与读入的字符进行比较,并且 count+=1。

于 2013-09-27T14:00:42.970 回答