Python中的字符串距离矩阵 [英] String Distance Matrix in Python

查看:148
本文介绍了Python中的字符串距离矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中计算字符串的Levenshtein距离矩阵

How to calculate Levenshtein Distance matrix of strings in Python

              str1    str2    str3    str4    ...     strn
      str1    0.8     0.4     0.6     0.1     ...     0.2
      str2    0.4     0.7     0.5     0.1     ...     0.1
      str3    0.6     0.5     0.6     0.1     ...     0.1
      str4    0.1     0.1     0.1     0.5     ...     0.6
      .       .       .       .       .       ...     .
      .       .       .       .       .       ...     .
      .       .       .       .       .       ...     .
      strn    0.2     0.1     0.1     0.6     ...     0.7

使用Ditance函数,我们可以计算2个单词之间的距离.但是这里我有1个包含n个字符串的列表.我想计算距离矩阵,然后再对单词进行聚类.

Using Ditance function we can calculate distance betwwen 2 words. But here I have 1 list containing n number of strings. I wanted to calculate distance matrix after that I want to do clustering of words.

推荐答案

只需使用

Just use the pdist version that accepts a custom metric.

Y = pdist(X, levensthein)

,对于 levensthein ,则可以按照以下建议使用Rosettacode的实现塔努

and for the levensthein then you can use the implementation of rosettacode as suggested by Tanu

如果您想要一个全平方矩阵,只需使用

If you want a full squared matrix just use squareform on the result:

Y = scipy.spatial.distance.squareform(Y)

这篇关于Python中的字符串距离矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆