
I’m trying to get my program to report the word that shows up the most in a text file. For example, if I type “Hello I like pie because they are like so good” the program should print out “like occurred the most.” I get this error when executing Option 3: KeyError: ‘h’
#Prompt the user to enter a block of text.
done = False
textInput = “”
while(done == False):
nextInput= input()
if nextInput== “EOF”:
break
else:
textInput += nextInput
#Prompt the user to select an option from the Text Analyzer Menu.
print(“Welcome to the Text Analyzer Menu! Select an option by typing a number”
“n1. shortest word”
“n2. longest word”
“n3. most common word”
“n4. left-column secret message!”
“n5. fifth-words secret message!”
“n6. word count”
“n7. quit”)
#Set option to 0.
option = 0
#Use the ‘while’ to keep looping until the user types in Option 7.
while option !=7:
option = int(input())
#The error occurs in this specific section of the code.
#If the user selects Option 3,
elif option == 3:
word_counter = {}
for word in textInput:
if word in textInput:
word_counter[word] += 1
else:
word_counter[word] = 1
print(“The word that showed up the most was: “, word)
解决方案
Instead of rolling your own counter, a better idea is to use Counters in the collections module.
>>> input = ‘blah and stuff and things and stuff’
>>> from collections import Counter
>>> c = Counter(input.split())
>>> c.most_common()
[(‘and’, 3), (‘stuff’, 2), (‘things’, 1), (‘blah’, 1)]
Also, as a general code style thing, please avoid adding comments like this:
#Set option to 0.
option = 0
It makes your code less readable, not more.
文章知识点与官方知识档案匹配,可进一步学习相关知识Python入门技能树首页概览208941 人正在系统学习中 相关资源:下拉通刷词软件v3.1.zip-其它代码类资源-CSDN文库
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!