在python 3中搜索查询中最相似的字符串。
TopSim的Python项目详细描述
在python 3中搜索查询中最相似的字符串。采用最先进的算法和数据结构以获得最佳效率。对于灵活性和效率,现在只支持基于集合的相似性,包括^ a4}和Tversky。
安装
这个包在pypi上提供。只需使用pip3 install -U TopSim
来安装它。
cli用法
你可以简单地在终端上使用算法。
Usage:
topsim-cli <query> [options] [<file>]
Options:
-I Case-sensitive matching.
-k <k> Maximum number of search results. [default: 1]
--tie Include all the results with the same similarity of the "k"-th result. May return more than "k" results.
-s, --search Search the query within each line rather than against the whole line, by preferring partial matching of the line.
Tversky similarity is used instead of Jaccard similarity.
-e <e> Parameter for "tversky" similarity. [default: 0.001]
--mapping=<mapping> Map each string to a set of either "gram"s or "word"s. [default: gram]
--numgrams=<numgrams> Number of characters for each gram when mapping by "gram". [default: 2]
--quiet Do not print additional information to standard error.
- 查询与输入文件(或标准输入)的每一行匹配。
- 每一行及其相似性由制表符
\t
分隔。
API使用
或者,可以通过api使用该算法。
fromtopsimimportTopSimts=TopSim(["python2","python2.7","python3","python3.6",])print(ts.search("python",k=3))# Return each similarity and the respective line numbers.
- 请检查
topsim.py
以获取更多可选参数,如相似函数等。
示例
- 搜索最相似的行。
ls /usr/bin | topsim-cli "top"
top 1.0
- 搜索三条最相似的线。
ls /usr/bin | topsim-cli "top" -k 3
top 1.0
tops 0.5
iotop 0.4286
- 默认情况下,使用jaccard相似性,这将使查询和行的匹配具有相同的权重。
ls /usr/bin | topsim-cli "git" -k 5
git 1.0
wait 0.2857
git-shell 0.2727
pluginkit 0.2727
kinit 0.25
- 使用Tversky相似度,它将最大的权重放在匹配查询上。在长队中搜索时非常理想。
ls /usr/bin | topsim-cli "git" -k 5 -s
git 1.0
git-shell 0.7489
pluginkit 0.7489
git-cvsserver 0.7481
git-upload-pack 0.7478
- 对于
n
-gram映射,较高的n
for数可以获得更好的精度,但匹配较少。
ls /usr/bin | topsim-cli "git" -k 5 -s --numgrams=3
git 1.0
git-shell 0.5993
git-cvsserver 0.5988
git-upload-pack 0.5986
git-receive-pack 0.5984
- 完全支持中文/日文/韩文。
cat test
地三鲜 红烧肉 烤全牛 木须肉 土豆炖牛肉
cat test | topsim-cli "牛肉" -k 3 -s
土豆炖牛肉 0.666 红烧肉 0.3332 木须肉 0.3332
提示
我强烈建议使用pypy而不是cpython来运行脚本以获得最佳性能。