在python中搜索文本文件中输入的单词

时间:2013-05-31 11:46:25

标签: python list text for-loop while-loop

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

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%的字母或更多匹配)。 / p>

非常感谢任何帮助

3 个答案:

答案 0 :(得分: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:块就会运行。

答案 1 :(得分: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

您可以调整“截止”和其他参数 - 查看get_close_matches

difflib module的文档

你可能要做的是查看:https://pypi.python.org/pypi/aspell-python/1.13这是aspell库周围的Python包装器,它可以提供更好的建议,也可以扩展到多个字典。< / p>

答案 2 :(得分:0)

你可以这样做:

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")

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