我正在研究檢查英語單詞之間相似性的算法。Python:通過避免重複相同的比較來加速我的循環
已經定義了一個名爲'相似性'的函數,我檢查整個單詞列表以檢查相似單詞,如果兩個單詞之間的相似性非常高(= 1),算法會將兩個單詞中的一個更改爲另一個。
這裏是邏輯:
list_of_word = [word1, word2, word3, word4]
假設有WORD1和word4之間非常高的相似性。
結果:
list_of_word = [word1, word2, word3, word1]
通常情況下,我只需要循環播放,所採取的措施將是這樣的:
- 取字1時,比較字詞1,word2和WORD3,word4
- 取word2,比較word1,word2,word3,word4
- 取word3,比較word1,word2,word3,word4
- 把word4,比較word1,word2,word3,word4
但是,有一些無用和重複的操作。例如,我不必一次比較字1和字2。
問題是我必須經過100萬字,它可能需要很多天才能運行。
有什麼建議嗎?
這裏是我使用的那一刻代碼:
from nltk.corpus import wordnet as wn
from itertools import product
def similarity(wordx,wordy):
sem1, sem2= wn.synsets(wordx), wn.synsets(wordy)
maxscore = 0
for i,j in list(product(*[sem1,sem2])):
score = i.path_similarity(j) # Wu-Palmer Similarity
maxscore = score if maxscore < score else maxscore
return maxscore
def group_high_similarity(target_list,tc):
result = target_list[:]
num_word = len(result)
for word in result:
wordx = word
i = 0
while i<len(result):
wordy = result[i]
value = similarity(wordx,wordy)
if value >= tc:
result[i] = wordx
if wordy != wordx :print wordy+"---> "+ wordx
i += 1
return result
你可以使用['itertools.combinations(即,2)'](https://docs.python.org/3/library/itertools.html#itertools.combinations)避免比較相同的話多個時間,但還有很多比較...... – Delgan