我要解决的问题是读取包含单词列表的文件。然后计算每个单词中的元音个数,并在表格中显示每个单词及其元音数和单词中的元音总数,最后显示所有单词中的元音总数。
我正在尝试通过 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/