【发布时间】:2014-04-11 00:44:47
【问题描述】:
我一直在阅读与分组相似词相关的其他一些链接(What is a good strategy to group similar words? 和 Fuzzy Group By, Grouping Similar Words)。我很好奇(1)是否有人可以指导我在第二个链接中找到的一种算法如何工作,以及(2)编程风格与我自己的“幼稚”方法相比如何?
如果你甚至可以回答 1 或 2,我会给你一个赞成票。
(1) 有人可以帮我看看这里发生了什么吗?
class Seeder:
def __init__(self):
self.seeds = set()
self.cache = dict()
def get_seed(self, word):
LIMIT = 2
seed = self.cache.get(word,None)
if seed is not None:
return seed
for seed in self.seeds:
if self.distance(seed, word) <= LIMIT:
self.cache[word] = seed
return seed
self.seeds.add(word)
self.cache[word] = word
return word
def distance(self, s1, s2):
l1 = len(s1)
l2 = len(s2)
matrix = [range(zz,zz + l1 + 1) for zz in xrange(l2 + 1)]
for zz in xrange(0,l2):
for sz in xrange(0,l1):
if s1[sz] == s2[zz]:
matrix[zz+1][sz+1] = min(matrix[zz+1][sz] + 1, matrix[zz][sz+1] + 1, matrix[zz][sz])
else:
matrix[zz+1][sz+1] = min(matrix[zz+1][sz] + 1, matrix[zz][sz+1] + 1, matrix[zz][sz] + 1)
return matrix[l2][l1]
import itertools
def group_similar(words):
seeder = Seeder()
words = sorted(words, key=seeder.get_seed)
groups = itertools.groupby(words, key=seeder.get_seed)
(2) 在我的方法中,我有一个要分组的字符串列表,称为 residentyList 并使用默认字典。
Array(['Psychiatry', 'Radiology Medicine-Prelim',
'Radiology Medicine-Prelim', 'Medicine', 'Medicine',
'Obstetrics/Gynecology', 'Obstetrics/Gyncology',
'Orthopaedic Surgery', 'Surgery', 'Pediatrics',
'Medicine/Pediatrics',])
我努力分组。我基于 uniqueResList,即 np.unique(residencyList)
d = collections.defaultdict(int)
for i in residencyList:
for x in uniqueResList:
if x == i:
if not d[x]:
#print i, x
d[x] = i
#print d
if d[x]:
d[x] = d.get(x, ()) + ', ' + i
else:
#print 'no match'
continue
【问题讨论】:
-
你要进行什么样的比较?长度相似度?你研究过 NLTK 吗?
-
直接匹配。是的
标签: python