计算列表中元素的频率,我必须按字母顺序打印这些元素

时间:2016-10-24 18:55:37

标签: python python-2.7 python-3.x

我有问题。我必须计算列表中元素的频率,我必须按字母顺序打印这些元素。任务是:https://1drv.ms/i/s!AqbJai99OU_ejy-jF_wOYaQCFjHR

我用这种方式:

**>>>from collections import Counter
>>>text= "he he he he she it she it she it and and and "
>>>words=text.split()
>>>counter=Counter(words)
>>>top_three=counter.most_common(4)
>>>top_three.sort(key=lambda x: (-x[1], x[0]))
>>>print(top_three)**

但是当我进行测试运行时,我遇到了这个问题:https://1drv.ms/i/s!AqbJai99OU_ejzBadWfydEv6oGpa

我知道我必须使用count_words函数,但我不知道该怎么做。 如果您知道,请写信给我:D

1 个答案:

答案 0 :(得分:0)

这是一种更简单的方法来获取类似单词的计数并对它们进行排序。

text = 'he he he he she it she it she it and and and'

wordlist = text.split()
wordlist.sort()

wordfreq = []
for w in wordlist:
    wordfreq.append(wordlist.count(w))
    print(w)

print()
print("String\n" + text +"\n")
print("List\n" + str(wordlist) + "\n")
print("Frequencies\n" + str(wordfreq) + "\n")

下面的@ D.Tarik代码可以根据需要进行工作。如果您认为答案是正确的并且帮助了您,请接受答案。

def count_word(text):

    wordlist = text.split()
    wordlist.sort()
    my_list = []

    for i in wordlist:
        if i not in my_list:
            word_count = wordlist.count(i)
            my_list.append((i,word_count))
    print(set(my_list))


count_word('he he he he she it she it she it and and and')

输出:

{('he', 4), ('and', 3), ('it', 3), ('she', 3)}