Python 拼写检查及建议
我正在做一个程序,这个程序会接收一个输入,然后检查这个输入是否在一个文件里的字典中拼写正确。不过,我还想给出一两个建议,告诉用户他们可能想表达的意思。有没有什么建议可以实现这个功能?我找到了一些模块可以做到这一点,但它们并不是针对特定文件里的字典。任何帮助都非常感谢!!
这是我现在的代码:
def getDictionary():
theDictionary = open("theDictionary.txt", "r")
dictionaryList = []
for eachLine in theDictionary:
splitLines = eachLine.split()
dictionaryList.append(splitLines[0])
theDictionary.close()
return dictionaryList
def spellChecker(theFile, theDictionary):
lowerItems = theFile.lower()
wordList = lowerItems.split()
wrongList = []
for item in wordList:
if item not in theDictionary:
result = False
wrongList.append(item)
else:
result = True
wrongItem = ""
return (result, wrongList)
def main():
theDictionary = getDictionary()
theText = getFile()
theInput = input("Input some words here:")
result, wrongList=spellChecker(theInput,theDictionary)
if result:
print("There are no spelling errors in the sentence! Hooray!")
else:
if len(wrongList) == 1:
print('There is a spelling error in the sentence! The word that is wrong is "' + str(wrongList) + '".')
elif len(wrongList) > 1:
print('There are some spelling errors in the sentence! The words that are wrong are"' + str(wrongList) + '".')
main()
1 个回答
3
你可以看看标准库里的 difflib 模块。这个模块可以帮助你进行近似字符串匹配,听起来正是你需要的功能。
其实你的字典是放在文件里还是别的地方并不重要,因为你最终都是把它加载到一个列表里。你可以关注一下这个模块里的 get_close_matches() 方法。