在Python字典中动态创建键和值

时间:2014-09-08 07:04:56

标签: python variables python-3.x dictionary

我想解决的问题是读取包含单词列表的文件。然后计算每个单词中元音的数量,并显示表格中的每个单词及其元音的数量和单词中的总元音,最后显示所有单词中的元音总数。

我试图通过for循环读取文件并创建与每个单词相关联的字典来解决问题,如

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

我的问题是我不知道如何在变量因循环而改变时创建字典。我刚刚结束了空字典。

这是我的输出http://imgur.com/mksgdTc

的屏幕截图

我在该文件中的测试代码是密西西比加州威斯康星州的所有不同行。

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.")

2 个答案:

答案 0 :(得分:3)

关注这一部分 - word在循环的每次迭代中被重新指定为空字典:

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

但是,现在注释word = {}会在从文件中读取第一个元音时抛出错误(因为现在dict不是空的)。请记住,word是您正在迭代的文本文件中的当前行,因此word['u_count'] = word_u_count被解释为更改字符串中字符的指令。 Python字符串是不可变的,因此会抛出错误。

你的程序比它需要的时间长得多 - 当你注意到代码中的重复时,考虑重构以利用循环和迭代,使程序更简洁。您可以将用于计算单词中字母的所有逻辑分成一个过程:

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))

然后您可以调用文件中的每个单词。

答案 1 :(得分:1)

在Python 2中我会做这样的事情......

#! /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()