我有两本字典。每本词典都收录了单词。有些词很常见,有些则不常见。我想要显示输出常用单词frequency1 frequency2和频率和。我该怎么做呢?我必须找到前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)
发布于 2021-01-15 15:21:36
假设字典中的每个单词都有单独的频率,我们可以做一些更简单的事情。比如..。
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])
发布于 2021-01-15 15:25:17
由于不允许使用Counter
,因此可以使用字典实现相同的功能。让我们定义一个函数来返回一个字典,其中包含给定列表中所有单词的计数。字典有一个get()
函数,用于获取给定键的值,同时还允许您在找不到键时指定默认值。
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
中所有独特的单词。然后我们将这两个词转换为集合,然后找到它们的intersection以获得常用词。
common_words = words1.intersection(words2)
现在你已经知道了常用词,打印它们和它们的计数应该很简单:
for w in common_words:
print(f"{w}\t{count1[w]}\t{count2[w]}\t{count1[w] + count2[w]}")
https://stackoverflow.com/questions/65738411
复制