Python 在字典中反复查找最常用的单词
我快速编写了一段代码,检查用户输入的单词列表,并计算用户输入的相同单词的数量。如果输入print,则应打印使用频率最高的单词以及使用次数(例如) “你好”这个词已经用了12次了 我只是不知道如何让它在字典中反复查找最常用的单词 这是密码Python 在字典中反复查找最常用的单词,python,python-3.x,Python,Python 3.x,我快速编写了一段代码,检查用户输入的单词列表,并计算用户输入的相同单词的数量。如果输入print,则应打印使用频率最高的单词以及使用次数(例如) “你好”这个词已经用了12次了 我只是不知道如何让它在字典中反复查找最常用的单词 这是密码 d = {} L2 = [] Counter = 0 checker = -1 while True: Text = str(input('enter word ')) Text = Text.lower() if Text in ['q',
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)
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