通过字典迭代找到最常用的单词

时间:2017-06-24 02:55:09

标签: python python-3.x

我快速编写了一些代码,用于检查用户输入单词列表,并计算用户键入的相同单词的数量。如果输入打印,则应该打印最常用的单词以及例如使用它的次数 “你好”这个词是'已被使用' 12'时 我只是不确定如何让它迭代字典并找到最常用的单词

这是代码

d = {}
L2 = []
Counter = 0
checker = -1

while True:
    Text = str(input('enter word '))
    Text = Text.lower()

if Text in ['q', 'Q']:
    break

if Text in ['Print', 'print']:
    for word in L2:
        if word not in d: 
            counter = L2.count(word)
            d[word] = counter

#This part does not work
    for value in d[0]:
        if checker < value:
            checker = value
    print(checker)  

#This part does         
L2.append(Text) 

1 个答案:

答案 0 :(得分:1)

d = {}
L2 = []

while True:
    text_input = input('enter word ') # input by default stores values in string format
    text_input = text_input.lower()

    if text_input == 'q': # you have used text_input.lower() so you don't need to use it is 'q' or 'Q' it will never be 'Q'
        break

    elif text_input == 'print':
        for item in set(L2): # set(L2) will only keep unique values from list L2
            d[item] = L2.count(item)  # counts for all unique items and append it to dictionary
        for word, count in d.items(): # by using this loop you can print all possible max values i.e. if two word has same max occurance it will print both
            if count == max(d.values()):
                print("Word : {} repeated {} times.".format(word, count))

    else:      
        L2.append(text_input) # input is neither 'q' nor 'print' hence append word in list