Stumped: Can't get my simple script to work right

I am working on a function that will count user-specified letters in a block of text or a text file. I keep thinking I have it set up right, but it won’t provide me with any output.

Here is a screenshot of my editor (code text is below the screenshot):

test_text = “”“hahsdhdicocmioehgpdkepdhgnNDFOldkdisnOIBVYo
djdUDISNEisjdkeldoxpsjdufbgoshguycbkgitpshjeqwy”""

def letter_counter(txt, letters_to_count):
“”“returns the number of times specified letters appear in a file”""

# convert letters_to_count string to a list, then to a dictionary
letters_list = list(letters_to_count)
letters2count = dict.fromkeys(letters_list, 0)

# create an empty dictionary for the count
letter_dict = {}

# opens specified file
### f = open(path_to_file)

# reads file into variable: text
### text = f.read()

# convert text to all lowercase: text_lower
text_lower = txt.lower()


# check contents of file against letters_to_count dictionary
for letter in text_lower:
    if letter in letter_dict.keys():
        letter_dict[letter] += 1
        
    else:
        letter_dict[letter] = 1

# return letter_dict
return letter_dict
print(letter_dict) 

letter_counter(test_text,‘aeiou’)

Did you coded it all at once and then run it?

Try to code in chunks as @zedshaw points out in his book:

Code a little
Run a little
Fix a little

So you will find your errors and learn a lot.

Having a quick look it seems you are not actually using the ‘letters2count’ variable in your code.

If you add it in the loop, which I think was intended, you’ll get some output, but it will be the start of your next investigation into why the dict is not capturing the letter count :wink:

# check contents of file against letters_to_count dictionary
for letter in text_lower:
    if letter in letter2count.keys():
        letter_dict[letter] += 1
    else:
        letter_dict[letter] = 1

I think @gpkesley is right. ‘letters2count’ is the dict that holds your results, so that’s the one that needs to store the counts and get returned when the function is done. Here’s a version that works I think. For this example I took out the code that loads the test_text from a file.

def letter_counter(test_text, letters_to_count):

    # convert letters_to_count string to a list, then to a dictionary
    letters_list = list(letters_to_count)
    letters2count = dict.fromkeys(letters_list, 0)
    
    # check contents of file against letters_to_count dictionary
    for letter in test_text.lower():
        if letter in letters2count.keys():
            letters2count[letter] += 1

    return letters2count

test_text = 'hahsdhdicocmioehgpdkepdhgnNDFOldkdisnOIBVYodjdUDISNEisjdkeldoxpsjdufbgoshguycbkgitpshjeqwy'
letters2count = letter_counter(test_text, 'aeiou')
print(f"Letter frequency: {letters2count}")
2 Likes