2013-05-31 118 views
1

因此,基本上我有一个文本文件中的单词列表,我希望能够搜索匹配的单词时用户输入一个检查拼写,这是到目前为止,我有什么。在python中搜索文本文件中的输入词

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 

我是新来的蟒蛇,最终我希望用户能够输入的词,如果拼写不正确,程序应该打印出匹配的单词列表(字母或以上的75%匹配)。

任何帮助,将不胜感激

+1

为什么你的代码中有'break'? – neelsg

回答

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

这需要一个输入,打开然后将文件通过线检查线路,如果输入字线相匹配的字典,如果它是它打印的消息,其他明智的,如果它没有行左打印输入词不在字典中。

+1

'while line'和'.readline()'看起来有些复杂......为什么不只是'为f'线? –

+0

冲,这是一个更好的方式说出来。已经更新了我的答案+1 – Noelkd

+1

另外,从行中删除'\ n',而不是将其添加到字符串......'如果line.strip()== wordCheck'和'str(wordCheck) ''是多余的,因为'raw_input'总是一个字符串 –

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:块将运行。

+0

为什么这会降低投票率? – TerryA

+0

解决了不搜索位,但现在它打印文件的每一行(10000 +词)我的else语句我只是希望它运行,当它发现的东西打印出结果 – Johnnerz

+0

@JohnConneely它不应该打印每行都有'else',但是只有在循环后如果没有调用'break' – TerryA

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_matchesdifflib module

什么你可能想要做的就是看看:https://pypi.python.org/pypi/aspell-python/1.13是绕aspell库,which'll做的更好建议,并会扩展到多个字典以及一个Python包装。

相关问题