Python:找到显示最多的单词? [英] Python: Finding the word that shows up the most?

查看:217
本文介绍了Python:找到显示最多的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的程序报告文本文件中显示最多的单词.例如,如果我键入你好,我喜欢馅饼,因为它们是如此的好",则程序应打印出最常发生的情况".执行选项3时出现此错误:KeyError:'h'

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:找到显示最多的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆