1

所以基本上我在一个文本文件中有一个很大的单词列表,当用户输入一个来检查拼写时,我希望能够搜索匹配的单词,这就是我到目前为止所拥有的。

f = open('words.txt', 'r')
wordCheck = input("please enter the word you would like to check the spelling of: ")

for line in f:
    if 'wordCheck' == line:
        print ('That is the correct spelling for '+wordCheck)
    else:
        print ( wordCheck+ " is not in our dictionary")
    break

当我输入一个单词时,我会立即得到 else 语句,我认为它甚至不会读取文本文件。我应该改用while循环吗?

while wordCheck != line in f

我是 python 的新手,最终我希望用户能够输入一个单词,如果拼写不正确,程序应该打印出匹配单词的列表(75% 的字母或更多匹配)。

任何帮助将不胜感激

4

3 回答 3

1

你可以这样做:

wordCheck = raw_input("please enter the word you would like to check the spelling of: ")
with open("words.txt", "r") as f:
    found = False    
    for line in f:
        if line.strip() == wordCheck:
            print ('That is the correct spelling for '+ wordCheck)
            found = True
            break
    if not found:
        print ( wordCheck+ " is not in our dictionary")

这需要一个输入,打开文件然后逐行检查输入单词是否与字典中的行匹配,如果它打印消息,否则如果没有剩余行打印输入单词不在字典中。

于 2013-05-31T11:59:15.227 回答
0

因为您只在第一行中断之前循环了它。

wordCheck = input("please enter the word you would like to check the spelling of: ")
with open('words.txt', 'r') as f:
    for line in f:
        if wordCheck in line.split():
            print('That is the correct spelling for '+wordCheck)
            break
    else:
        print(wordCheck + " is not in our dictionary")

这里for/else使用了,因此如果在任何行中都找不到该单词,则该else:块将运行。

于 2013-05-31T11:48:03.837 回答
0

它不会按照正确的拼写算法进行拼写,但您可以找到类似的单词:

from difflib import get_close_matches

with open('/usr/share/dict/words') as fin:
    words = set(line.strip().lower() for line in fin)

testword = 'hlelo'
matches = get_close_matches(testword, words, n=5)
if testword == matches[0]:
    print 'okay'
else:
    print 'Not sure about:', testword
    print 'options:', ', '.join(matches)

#Not sure about: hlelo
#options: helot, hello, leo, hollow, hillel

您可以调整“截止”和其他参数 - 检查difflib 模块中get_close_matches的文档

您可能想要做的是看一下:https ://pypi.python.org/pypi/aspell-python/1.13这是一个围绕aspell库的 Python 包装器,它会提供更好的建议并将扩展到多个字典也是。

于 2013-05-31T11:52:52.853 回答