Python:将列表元素的出现次数及其总计数添加到另一个列表中,避免添加重复项

Python: Add occurrences of a list element and its total count to another list, avoid adding duplicates

我有一个包含句子的文本语料库。 我希望计算每个单词出现的次数并避免多次添加任何单词(例如多次出现的','必须添加一次到 return 类似 ',': 2047

期望的输出:'partner': 7, 'meetings': 7, '14': 7, 'going': 7,等等。 我意识到我需要使用 set() 来避免重复。但我不知道怎么办。目前,我通过说 append only if not already in occurrences

来避免添加列表中已经存在的元素

但是这不起作用,因为我在结果中多次得到 ',':2047

我在示例代码中避免了列表推导式以增加 reader 的理解力! :P

统计单词[i]在单词

中的出现次数
occurrences = []
for i in range(1, words.__len__() - 1):
    if words[i-1] not in occurrences:
        occurrences.append((words[i - 1], words.count(words[i - 1])))
print(occurrences)

使用collections.Counter:

word_count = Counter(words)

根据这个答案here我应该像这样使用 Counter():

from collections import Counter
ctr = Counter()
    for word in words:
        ctr[word] += 1
    print(ctr)