Singh2013
Singh2013

Reputation: 179

Python Count Certain 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()

I am trying to count certain character, for example, if I was to put "W" in the char input prompt, It should count only W. How would I do that? I am trying to do the recursion in the def string function

Thank you.

Upvotes: 0

Views: 2859

Answers (5)

Spaceghost
Spaceghost

Reputation: 6985

Use the built-in count function:

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

3

Upvotes: 1

Óscar López
Óscar López

Reputation: 236034

This problem is easier/more efficient to solve using a loop, but if you really, really want to write a recursive solution, let's see how to do it. First example, how to count the number of lower case letters in a string (this is the correct implementation of your string() function):

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

The above will return the number of lower case letters in the input string, or throw an exception if a non-letter character was found. Notice that you can't just print a message if a non-letter character appears, it's necessary to stop the recursion, too - that's why I'm raising an exception.

Second example, how to count the number of occurrences of a character in a string (this answers the question in the title), it's similar to the previous example, but it only counts the character passed as parameter:

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

Upvotes: 1

jbaiter
jbaiter

Reputation: 7109

Here is a solution without recursion and regular expressions, just using built-ins.

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

Upvotes: 1

John Greenall
John Greenall

Reputation: 1690

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!

Upvotes: 0

mjhalwa
mjhalwa

Reputation: 533

I'd suggest you to take the file or whatever string as a string-variable and then go with a for-loop over the single elements of the string and compare each char to the char read in and count+=1.

Upvotes: 0

Related Questions