简单的Python文件I / O拼写检查程序

时间:2019-05-04 22:01:31

标签: python-3.x string file-io text-files spell-checking

对于一个类,我必须创建一个简单的拼写检查程序,该程序将两个文件作为输入,一个文件包含正确拼写的单词,另一个文件包含带有几个拼写错误的单词的段落。我以为我已经知道了,但是我遇到了一个从未见过的错误。程序完成后,出现错误:

<function check_words at 0x7f99ba6c60d0>

我从未见过此事,也不知道这意味着什么,将不胜感激使该程序正常运行的任何帮助。程序代码如下:

import os
def main():
    while True:
        dpath = input("Please enter the path to your dictionary:")
        fpath = input("Please enter the path to the file to spell check:")
        d = os.path.isfile(dpath)
        f = os.path.isfile(fpath)

        if d == True and f == True:
            check_words(dpath, fpath)
            break

    print("The following words were misspelled:")
    print(check_words)

def linecheck(word, dlist):
    if word in dlist:
        return None
    else:
        return word

def check_words(dictionary, file_to_check):
    d = dictionary
    f = file_to_check
    dlist = {}  
    wrong = []  


    with open(d, 'r') as c:
        for line in c:
            (key) = line.strip()
            dlist[key] = ''

    with open(f, 'r') as i:
        for line in i:
            line = line.strip()
            fun = linecheck(line, dlist)
            if fun is not None:
                wrong.append(fun)

    return wrong

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:3)

这不是错误,它完全按照您的指示进行操作。

此行:

print(check_words)

您正在告诉它打印功能。您看到的输出只是Python打印的函数名称及其地址:“打印函数”。

答案 1 :(得分:2)

是,不要print(check_words),不要print(check_words())

此外,将check_words(dpath, fpath)更改为misspelled_words = check_words(dpath, fpath)

然后将print(check_words)更改为print(misspelled_words)

最终代码(进行了一些修改):

import os
def main():
    while True:
        dpath = input("Please enter the path to your dictionary: ")
        fpath = input("Please enter the path to the file to spell check: ")
        d = os.path.isfile(dpath)
        f = os.path.isfile(fpath)

        if d == True and f == True:
            misspelled_words = check_words(dpath, fpath)
            break

    print("\nThe following words were misspelled:\n----------")
    #print(misspelled_words) #comment out this line if you are using the code below

    #optional, if you want a better looking output

    for word in misspelled_words:   # erase these lines if you don't want to use them
        print(word)                 # erase these lines if you don't want to use them

    #------------------------ 


def linecheck(word, dlist):
    if word in dlist:
        return None
    else:
        return word

def check_words(dictionary, file_to_check):
    d = dictionary
    f = file_to_check
    dlist = {}  
    wrong = []  


    with open(d, 'r') as c:
        for line in c:
            (key) = line.strip()
            dlist[key] = ''

    with open(f, 'r') as i:
        for line in i:
            line = line.strip()
            fun = linecheck(line, dlist)
            if fun is not None:
                wrong.append(fun)

    return wrong

if __name__ == '__main__':
    main()