[英]Python: Check if the sentence contains any word from List (with fuzzy match)
我想從給定list_of_keywords的句子中提取關鍵字。
我設法提取出確切的單詞
[word for word in Sentence if word in set(list_of_keywords)]
是否可以提取與給定list_of_keywords具有良好相似性的單詞,即兩個單詞之間的余弦相似度> 0.8
例如,給定列表中的關鍵字為“過敏”,現在該句子寫為
她對進餐后的堅果產生了嚴重的過敏反應。
“過敏”和“過敏”之間的余弦距離可計算如下
cosdis(word2vec('allergy'), word2vec('allergic'))
Out[861]: 0.8432740427115677
如何基於余弦相似度從句子中提取“過敏”?
def word2vec(word):
from collections import Counter
from math import sqrt
# count the characters in word
cw = Counter(word)
# precomputes a set of the different characters
sw = set(cw)
# precomputes the "length" of the word vector
lw = sqrt(sum(c*c for c in cw.values()))
# return a tuple
return cw, sw, lw
def cosdis(v1, v2):
# which characters are common to the two words?
common = v1[1].intersection(v2[1])
# by definition of cosine distance we have
return sum(v1[0][ch]*v2[0][ch] for ch in common)/v1[2]/v2[2]
list_of_keywords = ['allergy', 'something']
Sentence = 'a severe allergic reaction to nuts in the meal she had consumed.'
threshold = 0.80
for key in list_of_keywords:
for word in Sentence.split():
try:
# print(key)
# print(word)
res = cosdis(word2vec(word), word2vec(key))
# print(res)
if res > threshold:
print("Found a word with cosine distance > 80 : {} with original word: {}".format(word, key))
except IndexError:
pass
輸出 :
Found a word with cosine distance > 80 : allergic with original word: allergy
編輯 :
一線殺手:
print([x for x in Sentence.split() for y in list_of_keywords if cosdis(word2vec(x), word2vec(y)) > 0.8])
輸出 :
['allergic']
單詞的距離必須對照所有關鍵字進行檢查,並且僅在達到任何關鍵字的閾值時才包括在內。 我在原始列表理解中添加了一個額外的條件,而嵌套列表理解正是這樣做的。
def distance(words):
return cosdis(word2vec(words[0]), word2vec(words[1]))
threshold = 0.8
keywords = set(list_of_keywords)
matches = [word for word in Sentence if word in keywords and
any([distance(word, keyword) > threshold for keyword in keywords])]
senectence = 'a severe allergic reaction to nuts in the meal she had consumed.'
list_of_keywords = ['allergy','reaction']
word_list = []
for keyword in list_of_keywords:
for word in senectence.split():
if(cosdis(word2vec(keyword), word2vec(word)) > 0.8):
word_list.append(word)
或者如果您只想提取基於“過敏”關鍵字的單詞
[word for word in Sentence if cosdis(word2vec('allergy'), word2vec(word)) > 0.8]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.