Python 常用词频率及其频率和?

Python 常用词频率及其频率和?,python,python-3.x,Python,Python 3.x,我有两本字典。每本词典都包括单词。有些词很常见,有些则不然。我想演示如何输出公共字frequency1 frequency2和frequency sum。我该怎么做?我必须找到前20名 例如,我的输出必须如下所示: Common WORD frequ1. freq2 freqsum 1 print 10. 5. 15 2 number. 2. 1. 3. 3 program 19. 20. 39 这是我的密码:

我有两本字典。每本词典都包括单词。有些词很常见,有些则不然。我想演示如何输出公共字frequency1 frequency2和frequency sum。我该怎么做?我必须找到前20名

例如,我的输出必须如下所示:

Common WORD frequ1. freq2 freqsum
1 print      10.     5.      15
2 number.     2.     1.       3. 
3 program     19.    20.      39
这是我的密码:

commonwordsbook1andbook2 = []
for element in finallist1:
    if element in finallist2:
        commonwordsbook1andbook2.append(element)

common1 = {}
for word in commonwordsbook1andbook2:
    if word not in common1:
        common1[word] = 1
    else:
        common1[word] += 1
        
common1 = sorted(common1.items(), key=lambda x: x[1], reverse=True) #distinct2

for k, v in wordcount2[:a]:
    print(k, v)  

假设字典中每个单词都有各自的频率,我们可以做一些更简单的事情。像

print("Common Word | Freq-1 | Freq-2 | Freq-Sum")
for i in freq1:
   if i in freq2:
      print(i,freq1[i],freq2[i],freq1[i]+freq2[i])

由于不允许使用
计数器
,因此可以使用字典实现相同的功能。让我们定义一个函数来返回包含给定列表中所有单词计数的字典。字典有一个获取给定键的值的函数,同时还允许您在找不到该键时指定默认值

def countwords(lst):
    dct = {}
    for word in lst:
        dct[word] = dct.get(word, 0) + 1
    return dct


count1 = countwords(finallist1)
count2 = countwords(finallist2)

words1 = set(count1.keys())
words2 = set(count2.keys())
count1.keys()
将为我们提供
finallist1
中的所有唯一单词。 然后我们把这两个词都转换成集合,然后找到它们的对应词,得到常用词

common_words = words1.intersection(words2)
现在您已经知道了常用词,打印它们和它们的计数应该很简单:

for w in common_words:
    print(f"{w}\t{count1[w]}\t{count2[w]}\t{count1[w] + count2[w]}")

你能包括你正在使用的词典吗?您可以尝试使用collections模块中的Counter类。您能解释一下您的困境吗?看来你取得了一些进展。具体来说,您遇到了什么问题?我不允许使用计数器。@user3727648我不知道如何在输出上进行三重显示。@Camso您在这里遇到了什么错误?如何打印最大的20@Pranavhosangadia根据您的需要提供以下答案:如何打印最大的20@thelastackerman我们可以将整个内容存储在列表中,并根据总频率进行排序。