首页 > 解决方案 > 用段落中的常用词制作字典

问题描述

链接到问题陈述

请帮忙。我对如何执行此操作感到非常困惑:

这是我目前拥有的:

def similarityAnalysis(paragraph1, paragraph2):
    dict = {}
    for word in lst:
        if word in dict:
            dict[word] = dict[word] + 1
        else:
            dict[word] = 1
    for key, vale in dict.items():
        print(key, val)

标签: pythonlistdictionary

解决方案


见下文。

  • 为了找到常用词,我们使用集合交集
  • 对于计数,我们使用 dict

代码

lst1 = ['jack','Jim','apple']
lst2 = ['chair','jack','ball','steve']
common = set.intersection(set(lst1),set(lst2))
print('commom words below:')
print(common)
print()

print('counter below:')
counter = dict()
for word in lst1:
  if word not in counter:
    counter[word] = [0,0]
  counter[word][0] += 1
for word in lst2:
  if word not in counter:
    counter[word] = [0,0]
  counter[word][1] += 1
print(counter)

输出

commom words below:
{'jack'}

counter below:
{'jack': [1, 1], 'Jim': [1, 0], 'apple': [1, 0], 'chair': [0, 1], 'ball': [0, 1], 'steve': [0, 1]}

推荐阅读