user15592619
user15592619

Reputation:

Counting number of occurrences in a string

I need to return a dictionary that counts the number of times each letter in a predetermined list occurs. The problem is that I need to count both Upper and Lower case letters as the same, so I can't use .lower or .upper.

So, for example, "This is a Python string" should return {'t':3} if "t" is the letter being searched for.

Here is what I have so far...

def countLetters(fullText, letters):
    countDict = {i:0 for i in letters}
    lowerString = fullText.lower()
    for i in lowerString:
        if i in letters:
            countDict[i] += 1

    return countDict

Where 'letters' is the condition and fullText is the string I am searching.

The obvious issue here is that if the test is "T" rather than "t", my code won't return anything Sorry for any errors in my terminology, I am pretty new to this. Any help would be much appreciated!

Upvotes: -1

Views: 1362

Answers (6)

Use the Counter from the collections module

from collections import Counter
input = "Batuq batuq BatuQ"
bow=input.split(' ')
results=Counter(bow)
print(results)

output: Counter({'Batuq': 1, 'batuq': 1, 'BatuQ': 1})

Upvotes: 0

KarmaPenny
KarmaPenny

Reputation: 170

What you can do is simply duplicate the dict with both upper and lowercase like so:

def countLetters(fullText, letters):
    countDict = {}
    for i in letters:
        countDict[i.upper()]=0
        countDict[i.lower()]=0
    lowerString = fullText.lower()
    letters = letters.lower()
    for i in lowerString:
        if i in letters:
            countDict[i] += 1
            if (i!=i.upper()):
                countDict[i.upper()] +=1

    return countDict
print(countLetters("This is a Python string", "TxZY"))

Now some things you can also do is loop over the original string and change countDict[i] += 1 to countDict[i.lower()] +=1

Upvotes: 0

Barmar
Barmar

Reputation: 780673

You're looping over the wrong string. You need to loop over lowerString, not fullString, so you ignore the case when counting.

It's also more efficient to do if i in countDict than if i in letter.

def countLetters(fullText, letters):
    countDict = {i.lower():0 for i in letters}
    lowerString = fullText.lower()
    for i in lowerString:
        if i in countDict:
            countDict[i] += 1

    return countDict

Upvotes: 0

Petr Fořt Fru-Fru
Petr Fořt Fru-Fru

Reputation: 996

Try it - like this:

def count_letters(fullText, letters):
    countDict = {i: 0 for i in letters}
    lowerString = fullText.lower()
    for i in lowerString:
        if i in letters:
            countDict[i] += 1
    return countDict

test = "This is a Python string."
print(count_letters(test, 't')) #Output: 3

Upvotes: 0

batuq
batuq

Reputation: 11

To ignore capitalization, you need to input = input = input.lower () .Lists all characters of the input text using list operations. It can also be used as a word counter if you scan the space character.

input = "Batuq batuq BatuQ" # Reads all inputs up to the EOF character

input = input.replace('-',' ')#Replace (-, + .etc) expressions with a space character.
input = input.replace('.','')
input = input.replace(',','')
input = input.replace("`",'')
input = input.replace("'",'')

#input= input.split(' ') #if you use it, it will sort by the most repetitive words
dictionary = dict()
count = 0
for word in input:
    dictionary[word] = input.count(word)
    
print(dictionary)

#Writes the 5 most repetitive characters
for k in sorted(dictionary,key=dictionary.get,reverse=True)[:5]:
    print(k,dictionary[k])

Upvotes: 1

datawrestler
datawrestler

Reputation: 1567

Would something like this work that handles both case sensitive letter counts and non case sensitive counts?

from typing import List

def count_letters(
    input_str: str,
    letters: List[str],
    count_case_sensitive: bool=True
):
    """
    count_letters consumes a list of letters and an input string
    and returns a dictionary of counts by letter. 
    """
    if count_case_sensitive is False:
        input_str = input_str.lower()
        letters = list(set(map(lambda x: x.lower(), letters)))
    # dict comprehension - build your dict in one line
    # Tutorial on dict comprehensions: https://www.datacamp.com/community/tutorials/python-dictionary-comprehension
    counts = {letter: input_str.count(letter) for letter in letters}
 
    return counts

# define function inputs    
letters = ['t', 'a', 'z', 'T']
string = 'this is an example with sTrings and zebras and Zoos'

# case sensitive
count_letters(
    string,
    letters,
    count_case_sensitive=True
)
# {'t': 2, 'a': 5, 'z': 1, 'T': 1}

# not case sensitive
count_letters(
    string,
    letters,
    count_case_sensitive=False
)
# {'a': 5, 'z': 2, 't': 3} # notice input T is now just t in dictionary of counts

Upvotes: 0

Related Questions