Created
December 17, 2020 15:04
-
-
Save Kasahs/ba97cafe56b06515cd8a1808544e7543 to your computer and use it in GitHub Desktop.
A python script to return all lines in the input file in descending order of edit distance from the input string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from difflib import ndiff | |
import sys | |
def distance(str1, str2): | |
a = 0 | |
r = 0 | |
for x in ndiff(str1, str2): | |
if x[0] == "-": | |
r += 1 | |
elif x[0] == "+": | |
a += 1 | |
return max(a, r) | |
def main(): | |
infile_path = sys.argv[1] | |
str1 = sys.argv[2] | |
with open(infile_path, "r") as infile: | |
lines = [] | |
for line in infile: | |
lines.append((distance(str1, line), line)) | |
s_lines = sorted(lines, key=lambda x: x[0], reverse=True) | |
print("\n".join([str(l[0]) + ", " + l[1] for l in s_lines])) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment