2013-05-31 121 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包裝。

相關問題