Skip to content

Commit

Permalink
Add substr_scorer (#159)
Browse files Browse the repository at this point in the history
* Add substr_scorer

Close #158

* Refactor a bit

* Rename to scorer.py
  • Loading branch information
liuchengxu authored Dec 15, 2019
1 parent 9c12bf2 commit c1a6481
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
17 changes: 14 additions & 3 deletions pythonx/clap/fzy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@
# -*- coding: utf-8 -*-

import vim
from clap.fzy_impl import fzy_scorer

from clap.scorer import fzy_scorer, substr_scorer

def fuzzy_match_py(query, candidates):

def apply_score(scorer, query, candidates):
scored = []

for c in candidates:
score, indices = fzy_scorer(query, c)
score, indices = scorer(query, c)
if score != float("-inf"):
scored.append({'score': score, 'indices': indices, 'text': c})

return scored


def fuzzy_match_py(query, candidates):
if ' ' in query:
scorer = substr_scorer
else:
scorer = fzy_scorer

scored = apply_score(scorer, query, candidates)
ranked = sorted(scored, key=lambda x: x['score'], reverse=True)

indices = []
Expand Down
19 changes: 19 additions & 0 deletions pythonx/clap/fzy_impl.py → pythonx/clap/scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,22 @@ def fzy_scorer(niddle, haystack):
return score(niddle, haystack)
else:
return SCORE_MIN, None


def substr_scorer(niddle, haystack):
positions, offset = [], 0
niddle, haystack = niddle.lower(), haystack.lower()
for niddle in niddle.split(" "):
if not niddle:
continue
offset = haystack.find(niddle, offset)
if offset < 0:
return float("-inf"), None
niddle_len = len(niddle)
positions.extend(range(offset, offset + niddle_len))
offset += niddle_len
if not positions:
return 0, positions
match_len = positions[-1] + 1 - positions[0]
return -match_len + 2 / (positions[0] + 1) + 1 / (
positions[-1] + 1), positions

0 comments on commit c1a6481

Please # to comment.