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

标签 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

我在文件中的测试代码是 Mississippi California Wisconsin 都在不同的行上。

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

最佳答案

关注本节——word 在循环的每次迭代中都被重新分配为一个空字典:

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

但是,当从文件中读取第一个元音时,注释 word = {} 现在会抛出错误(因为现在字典不是空的)。请记住 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))

然后您为文件中的每个单词调用它。

关于python - 在 Python 字典中动态创建键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25718949/

相关文章:

python - Raspberry Pi 中的硬币计数器 (RPi-GPIO)

python - 从字符列表中删除方括号

Python:当数据框中的行迭代在列的字符串中找到字母时添加一行

python-3.x - 在 discord.py 中删除机器人的消息

python - 重载加法、减法和乘法运算符

javascript - 优化代码仅定义一次变量,代码仅在变量处于更改功能时才起作用,而对于更改之外的代码我重新定义?

variables - 数据类型 Variable 与 VariableV2 之间有什么区别?

c - 文件中的全局静态变量与函数中的局部静态变量具有可比性吗?

python - xml.etree.ElementTree 与 lxml.etree : different internal node representation?

python - 为什么我无法在提交给 ProcessPoolExecutor 的可调用对象中创建/访问 future?