如何根据python中的这些提示解决句子中最常见的单词?

2024-06-16 14:54:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了这个代码,但它不是完美的,因为它返回的关键是最高的价值,但不返回一个先来的字母顺序。我如何让它返回字母表中第一个? 而且,我应该按照提示做,但我做的不同。根据提示我该怎么做?你知道吗

Complete the most_frequent() function below so that it returns the most frequently occurring word in a given string.

For example, if the input s is s = 'I scream you scream we all scream for ice cream', the result should be scream as it is the most frequent word in this sentence.

If there is a tie for the most common word, return only one result, the first (tied) word in alphabetical order.

"""Quiz: Most Frequent Word"""

def most_frequent(s):
    """Return the most frequently occuring word in s."""

    # HINT: Use the built-in split() function to transform the string s into an
    #       array
    words = s.split(" ")

    # HINT: Sort the new array by using the built-in sorted() function or
    #       .sort() list method

    # HINT: Iterate through the array and count each occurance of every word
    #       using the .count() list method

    dict = {}
    for word in words:
        dict[word] = words.count(word)



    # HINT: Find the number of times the most common word appears using max()
    result = max(dict, key=dict.get)

    # HINT: Locate the index of the most frequently seen word

    # HINT: Return the most frequent word. Remember that if there is a tie,
    #       return the first (tied) word in alphabetical order.


    return result



def test_run():
    """Test most_frequent() with some inputs."""
    print(most_frequent("cat bat mat mat cat")) # output: 'cat'
    print(most_frequent("betty bought a bit of butter but the butter was bitter")) # output: 'butter'


if __name__ == '__main__':
    test_run()

Tags: oftheinmostforifisfunction
2条回答

sorted中使用键参数。根据频率(值)从高到低排序,然后按键的顺序对元组进行排序

s='cat bat mat mat cat'
words = s.split(" ")
d={}
for i in words:
    d[i]=d.get(i,0)+1
sorted(d.items(),key=lambda x:(-x[1],x[0]),reverse=False)[0][0]  #'cat'

如果您想使用集合中的计数器来减少一些代码行

from collections import Counter
s='cat bat mat mat cat'
words = s.split(" ")
d=Counter(words)
sorted(d.items(),key=lambda x:(-x[1],x[0]),reverse=False)[0][0]  #'cat'

reverse=False是可选的

一点也不酷的解决方案:

s = 'I scream you scream we all scream for ice cream all'
d = dict()
for word in s.split(' '):
    if word in d:
        d[word] += 1
    else:
        d[word] = 0
k = sorted(list(d.items()), key = lambda x: (x[1], x[0]))
highest_freq = k[-1][1]
result = k[-1][0]
for i in reversed(range(len(k))):
    if k[i][1] < highest_freq:
        break
    else:
        result = k[i][0]
print(result)

相关问题 更多 >