問題陳述鏈接
請幫忙。我對如何執行此操作感到非常困惑:
這是我目前擁有的:
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)
uj5u.com熱心網友回復:
見下文。
- 為了找到常用詞,我們使用集合交集
- 為了計數,我們使用字典
代碼
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]}
uj5u.com熱心網友回復:
分析你的代碼如下:
您使用
dict作為保留關鍵字的變數名(用于創建字典)。通過使用它作為變數名,您將失去使用該dict函式的能力。該函式使用一個名為的變數
lst,該變數不是其引數之一。這個變數的值從何而來?在第二個 for 回圈中,您使用了變數名,
vale但隨后又參考了一個名為 的不同變數val。
否則,看起來不錯。可能還有其他問題,就我所知。
建議谷歌搜索以下內容,看看你找到了什么代碼
- “Python 計算段落中的單詞數”
更新: 有很多方法可以做到這一點,但這里有一個答案:
def word_counts(lst):
counts = {}
for word in lst:
counts[word] = counts.get(word, 0) 1
return counts
def similarityAnalysis(paragraph1, paragraph2):
lst1 = paragraph1.split()
lst2 = paragraph2.split()
counts1 = word_counts(lst1)
counts2 = word_counts(lst2)
common_words = set(lst1).intersection(lst2)
return {word: (counts1[word], counts2[word]) for word in common_words}
paragraph1 = 'one three two one two four'
paragraph2 = 'one two one three three one'
print(similarityAnalysis(paragraph1, paragraph2))
輸出:
{'three': (1, 2), 'one': (2, 3), 'two': (2, 1)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358209.html
上一篇:尋找最常見的元素
