3

我尝试解决此问题的方法是将用户的单词输入列表,然后使用 .count() 查看该单词在列表中出现的次数。问题是每当出现平局时,我都需要打印出现次数最多的所有单词。仅当我使用的单词不在出现相同次数的另一个单词中时,它才有效。例如:如果我按顺序使用 Jimmy 和 Jim,它只会打印 Jimmy。

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]
4

4 回答 4

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)]
于 2013-07-12T19:43:00.047 回答
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]
于 2013-07-12T19:44:59.900 回答
1

而不是连接到 common where"Jim" in "Fred|Jimmy|etc"是 true 使用列表来存储找到的最大值,然后 print "|".join(commonlist)

于 2013-07-12T19:45:10.343 回答
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 )
于 2013-07-12T20:03:20.610 回答