1

The problem I am trying to solve is reading in a file in that contains a list of words. Then counting the number of vowels in each word and display each word in a table along with the number of its vowels and the total vowels in the word, and at the end display the total number of vowels in all of the words.

I am trying to solve the problem by reading the file in through a for loop and creating a dictionary that is associated with every word like

mississippi['a_count' : 0, 'e_ocunt' : 0, 'i_count' : 4 ,'o_count' : 0, 'u_count' : 0, 'y_count' : 0]

My problem is that I am not sure how to create the dictionaries as the variable changes due to a loop. I am just ending up with empty dictionaries.

here's a screenshot of my output https://i.sstatic.net/4yusw.jpg

my test code in the file is Mississippi California Wisconsin all on different lines.

try:
    word_file = open("vowel.txt", "r")

    count = 0
    dic = {}

    a_count = 0
    e_count = 0
    i_count = 0
    o_count = 0
    u_count = 0
    y_count = 0
    total_count = 0

    #this establishes the top of the table
    print('Number','{:>8}'.format('word'),'{:>8}'.format('A'),'{:>4}'.format('E'),'{:>4}'.format('I'),'{:>4}'.format('O'),'{:>4}'.format('U'),'{:>4}'.format('Y'),'{:>8}'.format('Total'))
    print("__________________________________________________________")


    for word in word_file:
        count+=1
        word = {}
        print(word)

        word_a_count = 0
        word_e_count = 0
        word_i_count = 0
        word_o_count = 0
        word_u_count = 0
        word_y_count = 0
        word_total_count = 0

        for letters in word:
            print(letters)
            if letters.lower() == "a":
                a_count+= 1
                total_count += 1
                word_a_count +=1
                word['a_count'] = word_a_count
            if letters.lower() == "e":
                e_count+= 1
                total_count += 1
                word_e_count +=1
                word['e_count'] = word_e_count
            if letters.lower() == "i":
                i_count+= 1
                total_count += 1
                word_i_count +=1
                word['i_count'] = word_i_count
            if letters.lower() == "o":
                o_count+= 1
                total_count += 1
                word_o_count +=1
                word['o_count'] = word_o_count
            if letters.lower() == "u":
                u_count+= 1
                total_count += 1
                word_u_count +=1
                word['u_count'] = word_u_count
            if letters.lower() == "y":
                y_count+= 1
                total_count += 1
                word_y_count +=1
                word['y_count'] = word_y_count

            print('Totals','{:>8}'.format('    '),'{:>8}'.format(word['a_count']),'{:>4}'.format\
            (word['e_count']),'{:>4}'.format(word['i_count']),'{:>4}'.format\
            (word['o_count']),'{:>4}'.format(word['u_count']),'{:>4}'.\
            format(word['y_count']))

    #this creates the bottom barrier of the table
    print("__________________________________________________________")

    #code for totals print
    print('Totals','{:>8}'.format('    '),'{:>8}'.format(a_count),'{:>4}'.format(e_count),'{:>4}'.format(i_count),'{:>4}'.format(o_count),'{:>4}'.format(u_count),'{:>4}'.format(y_count),'{:>6}'.format(total_count))

except IOError:
    print("The file does not seem to exists. The program is halting.")
5
  • 1
    Your output is text, you can easily copy and paste that here instead of using a screenshot. Commented Sep 8, 2014 at 7:06
  • @John Antony I think the most important thing here is : don't use a custom "a_count" string as key when you could use "a". your problem is about generating dynamically named variables (to be then used as keys so you are compounding the very problem a dict would sove for you) which is almost always a bad idea. Commented Sep 8, 2014 at 8:38
  • @Martijn Pieters I actually tried just pasting the output in at first but it distorted the table and I wanted to make sure everyone could see the same thing as me. Commented Sep 11, 2014 at 6:36
  • @JohnAnthony: We can help you format stuff like that; we usually won't type up text from a screenshot however. Commented Sep 11, 2014 at 6:48
  • Oh sorry I didnt know. If I need to type something like that up later should I go somewhere on the site and ask for help or should I just post it and you'll see it and be able to help me? Commented Sep 11, 2014 at 7:35

2 Answers 2

3

Focus on this section -- word is re-assigned as an empty dict on every iteration of the loop:

for word in word_file:
        count+=1
        word = {}

However, commenting word = {} out now throws an error when the first vowel is read from file (since now the dict isn't empty). Remember that word is the current line in the text file that you are iterating over, so word['u_count'] = word_u_count is interpreted as an instruction to change a character in the string. Python strings are immutable, so an error is thrown.

Your program is much longer than it needs to be - when you notice repetition in your code consider refactoring to take advantage of loops and iteration, to make your program more concise. You could separate all the logic for counting the letters in a word into one procedure:

def countletters(word, letterstocount):

    count = {}
    word = word.lower()

    for char in word:       
        if char in letterstocount:  
            if char in count:
                count[char] += 1
            else:
                count[char] = 1
    return count

#example call
vowels = "aeiou"
print(countletters('Arizona', vowels))

which you then call for each word in your file.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I thought my code was too long and was simply repeating itself in parts but I wasn't sure how to fix it let alone shorten it. This helped me to see how to get it working as well as shorten it and make it clearer .
1

In Python 2 I'd do something like this...

#! /usr/bin/env python

'''
Count vowels in a list of words & show a grand total

Words come from a plain text file with one word per line
'''

import sys

vowels = 'aeiouy'


def make_count_dict():
    ''' Create a dict for counting vowels with all values initialised to 0 '''
    return dict(zip(vowels, (0,)*len(vowels)))


def get_counts(d):
    return ' '.join('%2d' % d[k] for k in vowels) 


def count_vowels(wordlist):
    hline = '_'*45
    print '%3s: %-20s: %s' % ('Num', 'Word', ' '.join('%2s' % v for v in vowels))
    print hline

    total_counts = make_count_dict()
    for num, word in enumerate(wordlist, start=1):
        word_counts = make_count_dict()
        for ch in word.lower():
            if ch in vowels:
                word_counts[ch] += 1
                total_counts[ch] += 1
        print '%3d: %-20s: %s' % (num, word, get_counts(word_counts))

    print hline
    print '%-25s: %s' % ('Total', get_counts(total_counts)) 


def main():
    fname = len(sys.argv) > 1 and sys.argv[1]
    if fname:
        try:
            with open(fname, 'r') as f:
                wordlist = f.read().splitlines()
        except IOError:
            print "Can't find file '%s'; aborting." % fname
            exit(1)
    else:
        wordlist = ['Mississippi', 'California', 'Wisconsin']

    count_vowels(wordlist)


if __name__ == '__main__':
    main()

1 Comment

Great work, this allowed me to see another way to tackle the problem thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.