拼写检查算法输出所有内容而不仅仅是拼写错误(Python)?

2024-04-19 05:11:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上是在编写一个简单的拼写检查程序,提示您输入一个输入文件,然后分析输入文件中可能存在的拼写错误(通过使用二进制搜索查看单词是否在字典中),然后再将它们打印到输出文件中。 但是,目前,它输出输入文件中的所有内容,而不仅仅是错误。。。 我的代码如下:

import re

with open('DICTIONARY1.txt', 'r') as file:
    content = file.readlines()
    dictionary = []
    for line in content:
        line = line.rstrip()
        dictionary.append(line)

def binary_search(array, target, low, high):
    mid = (low + high) // 2
    if low > high:
        return -1
    elif array[mid] == target:
        return mid
    elif target < array[mid]:
        return binary_search(array, target, low, mid-1)
    else:
        return binary_search(array, target, mid+1, high)

input = input("Please enter file name of file to be analyzed: ")
infile = open(input, 'r')
contents = infile.readlines()
text = []
for line in contents:
    for word in line.split():
        word = re.sub('[^a-z\ \']+', " ", word.lower())
        text.append(word)
infile.close()
outfile = open('TYPO.txt', 'w')
for data in text:
    if data.strip() == '':
        pass
    elif binary_search(dictionary, data, 0, len(data)) == -1:
        outfile.write(data + "\n")
    else:
        pass

file.close
outfile.close

我好像不知道怎么了。:( 任何帮助都将不胜感激! 非常感谢。:)


Tags: 文件intargetforsearchdatareturnline
1条回答
网友
1楼 · 发布于 2024-04-19 05:11:37

我试着用len(data)替换len(dictionary),因为这对我来说更有意义,而且似乎在我非常有限的测试中起作用。你知道吗

我想你是把这个词的长度作为字典的上限。因此,如果您在查找单词“dog”,那么您只检查字典中的前3个单词,而且由于您的字典可能非常大,几乎没有找到每个单词(因此每个单词都在输出文件中)。你知道吗

相关问题 更多 >