Write a function named spelling_corrector.
函数应该检查输入字符串中的每个单词与correct_spells列表中的所有单词,并返回一个字符串,使得:
-
如果原始句子中的单词与单词中的单词完全匹配
correct_spells然后这个词没有被修改,它应该是
直接复制到输出字符串。 -
如果句子中的单词可以匹配correct_spells列表中的单词
通过替换,插入或删除单个字符,然后
word应该被correct_spelled中的正确单词替换
名单。 -
如果前两个条件都不成立,那么单词in
原始字符串不应该被修改,应该是直接的
复制到输出字符串。
笔记:
-
不要拼写检查一个或两个字母的单词(直接复制到
输出字符串)。 -
如果是平局,请使用correct_spelled列表中的第一个单词。
-
忽略大写,即将大写字母视为相同
作为小写字母。 -
输出字符串中的所有字符都应为小写
字母。 -
假设输入字符串仅包含字母字符和
空间。 (a-z和A-Z) -
删除单词之间的额外空格。
-
删除输出字符串开头和结尾的空格。
例子:
在此输入图像描述
注意:
-
在第一个例子中,'thes'没有被任何东西取代。
-
在第一个例子中,'case'和'car'都可以替换原始句子中的'cas',但选择'case'是因为它首先被遇到。
这是我尝试过的代码但不是很有用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def spelling_corrector(input_string,input_list): new_string = input_string.lower().split() count = 0 for x in new_string: for y in input_list: for i in y: if i not in x: count += 1 if count == 1: print(y) if len(x) == len(y) or x not in input_list: print(x) spelling_corrector("Thes is the Firs cas", ['that','first','case','car'])` |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | def replace_1(bad:str, good:str) -> bool: """Return True if bad can be converted to good by replacing 1 letter. """ if len(bad) != len(good): return False changes = 0 for i,ch in enumerate(bad): if ch != good[i]: return bad[i+1:] == good[i+1:] return False def insert_1(bad:str, good:str) -> bool: """Return True if bad can be converted to good by inserting 1 letter. """ if len(bad) != len(good) - 1: return False for i,ch in enumerate(bad): if ch != good[i]: return bad[i:] == good[i+1:] # At this point, all of bad matches first part of good. So it's an # append of the last character. return True def delete_1(bad:str, good:str) -> bool: """Return True if bad can be converted to good by deleting 1 letter. """ if len(bad) != len(good) + 1: return False return insert_1(good, bad) def correction(word:str, correct_spells:list) -> str: if len(word) < 3: return word if word in correct_spells: return word for good in correct_spells: if replace_1(word, good): return good if insert_1(word, good): return good if delete_1(word, good): return good return word def spelling_corrector(sentence:str, correct_spells:list) -> str: words = sentence.strip().lower().split() correct_lower = [cs.lower() for cs in correct_spells] result = [correction(w, correct_lower) for w in words] return ' '.join(result) tests = ( ('Thes is the Firs cas',"that first case car", 'thes is the first case'), ('programming is fan and easy',"programming this fun easy hook", 'programming is fun and easy'), ('Thes is vary essy',"this is very very easy", 'this is very easy'), ('Wee lpve Python',"we Live In Python", 'we live python'), ) if __name__ =="__main__": for t in tests: correct = t[1].split() print(t[0],"|", t[1],"|", t[2]) print("Result:", spelling_corrector(t[0], correct)) assert spelling_corrector(t[0], correct) == t[2] |