[英]Remove similar items from a list
我有一個單詞列表(將近7個項目),並且我想刪除與其他單詞幾乎相同的項目(即,如果我的單詞是“代理帳戶銀行協議”,我想刪除類似“代理帳戶銀行協議” )。
為了估計一個單詞是否接近另一個單詞,我使用了Python中來自水母包的Jaro距離。
我當前的代碼是:
corpus3 = ['Agency Account Bank Agreement', 'Agent', 'Agency Account Bank Agreement Pursuant',
'Agency Account Bank Agreement Notwithstanding', 'Agents', 'Agent', 'Reinvestment Period']
threshold = 0,85
for a, b in itertools.combinations(corpus3, 2):
if len(a.split()) >= 2 or len(b.split()) >= 2:
jf = jellyfish.jaro_distance(a, b)
if jf > threshold:
if a in new_corpus and b in new_corpus:
continue
else:
if len(a.strip()) < len(b.strip()):
kw = a
if not new_corpus:
new_corpus.append(a)
else:
for item in new_corpus:
jf = jellyfish.jaro_distance(kw, item)
if jf < threshold:
new_corpus.append(kw)
這就是我最后想要的:
new_corpus = ['Agency Account Bank Agreement', 'Agent', 'Reinvestment Period']
假設您有以下列表:
numchars = ['one', 'ones', 'two', 'twos', 'three', 'threes']
比方說,你相信, one
是太相似了ones
為你的口味,你只希望保留這兩個中的一個,這樣,你的修訂名單將類似於此:
numchars = ['ones', 'twos', 'threes']
您可以這樣做以消除您認為過於相似的內容:
for x in numchars:
if any(lower_threshold < jellyfish.jaro_distance(x, _x) and x != _x for _x in numchars):
numchars.remove(x)
根據您設置的閾值以及列表的順序,這可能會產生如下結果:
numchars = ['ones', 'twos', 'threes']
此例程中的主要邏輯在此行中:
if any(lower_threshold < jellyfish.jaro_distance(x, _x) and x != _x for _x in numchars):
這表示,如果列表numchars
任何成員與該列表中numchars
其自身的所有成員相比,相似度都大於您定義的lower_threshold
,則應從列表中刪除該成員,例如numchars.remove(x)
。 同樣, and x != _x
條件避免將成員注冊為and x != _x
自身過於相似。
但是可以這么說,這種三明治的肉是這樣的:
numchars.remove(x)
此語句確保一旦你刪除one
為是太相似ones
,下一次迭代中one
不在列表中的一員了,並不比ones
以這樣一種方式,將消除ones
為好。 這種方法最終將導致一個空列表。
一旦開始只希望保留復數形式或其他某些形式的相似匹配組,就可以打開另一整個蠕蟲罐。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.