我尝试解决此问题的方法是将用户的单词输入到列表中,然后使用.count()查看该单词在列表中的次数。问题是每当出现平局时,我需要打印所有出现次数最多的单词。只有当我使用的单词不在另一个出现相同次数的单词内时,它才有效。例如:如果按顺序使用吉米和吉姆,它只会打印吉米。
for value in usrinput:
dict.append(value)
for val in range(len(dict)):
count = dict.count(dict[val])
print(dict[val],count)
if (count > max):
max = count
common= dict[val]
elif(count == max):
if(dict[val] in common):
pass
else:
common+= "| " + dict[val]
答案 0 :(得分:5)
使用collections.Counter
课程。我会给你一个提示。
>>> from collections import Counter
>>> a = Counter()
>>> a['word'] += 1
>>> a['word'] += 1
>>> a['test'] += 1
>>> a.most_common()
[('word', 2), ('test', 1)]
您可以从此处提取单词和频率。
使用它从用户输入中提取频率。
>>> userInput = raw_input("Enter Something: ")
Enter Something: abc def ghi abc abc abc ghi
>>> testDict = Counter(userInput.split(" "))
>>> testDict.most_common()
[('abc', 4), ('ghi', 2), ('def', 1)]
答案 1 :(得分:1)
为什么不使用collections.defaultdict
?
from collections import defaultdict
d = defaultdict(int)
for value in usrinput:
d[value] += 1
要获得最常见的单词,按出现次数按降序排序:
print sorted(d.items(), key=lambda x: x[1])[::-1]
答案 2 :(得分:1)
而是连接到"Jim" in "Fred|Jimmy|etc"
为真的公共区域,使用列表存储找到的最大值,然后打印"|".join(commonlist)
。
答案 3 :(得分:1)
这是一个快速而肮脏的解决方案,根本不优雅,并且使用numpy。
import numpy as np
def print_common( usrinput ):
'''prints the most common entry of usrinput, printing all entries if there is a tie '''
usrinput = np.array( usrinput )
# np.unique returns the unique elements of usrinput
unique_inputs = np.unique( usrinput )
# an array to store the counts of each input
counts = np.array( [] )
# loop over the unique inputs and store the count for each item
for u in unique_inputs:
ind = np.where( usrinput == u )
counts = np.append( counts, len( usrinput[ ind ] ) )
# find the maximum counts and indices in the original input array
max_counts = np.max( counts )
max_ind = np.where( counts == max_counts )
# if there's a tie for most common, print all of the ties
if len( max_ind[0] ) > 1:
for i in max_ind[0]:
print unique_inputs[i], counts[i]
#otherwise just print the maximum
else:
print unique_inputs[max_ind][0], counts[max_ind][0]
return 1
# two test arrays which show desired results
usrinput = ['Jim','Jim','Jim', 'Jimmy','Jimmy','Matt','Matt','Matt']
print_common( usrinput )
usrinput = ['Jim','Jim','Jim', 'Jimmy','Jimmy','Matt','Matt']
print_common( usrinput )