2016-10-25 73 views
0

我在python中使用二進制搜索爲拼寫檢查器編寫了以下代碼,它工作正常,但輸出是反向的。例如,我寫了「hwllo world」,輸出是world hello而它是「世界你好」在使用二進制搜索的拼寫檢查器中的python錯誤

我的代碼如下:

import difflib 
    #L=[] 
    ch=[] 
    def binarySearch(alist, item): 
      first = 0 
      last = len(alist) - 1 
      while first <= last: 
       midpoint = (first + last) // 2 
       if alist[midpoint] == item: 
        return True 
       else: 
        if item < alist[midpoint]: 
        last = midpoint - 1 
       else: 
        first = midpoint + 1 
      return False 

    f = open('wordlist.txt', 'r').read().splitlines() 
    v=str(input("enter your sentence : ")).split() 


    for i in range(len(v)): 
     if binarySearch(f, v[i]) == True: 
      ch.append(v[i]) 


     elif binarySearch(f, v[i]) == False: 
      sugg = [] 
      for word in f: 
      if difflib.SequenceMatcher(None, v[i], word).ratio() >= 0.8: 
       sugg.append(word) 
      print(sugg) 

    for j in range (len(sugg)): 
      print("if you mean ",(sugg[j]),"press",(j)) 

    x=int(input()) 
    ch.append(sugg[x]) 

    print (' '.join(ch)) 

回答

0

這是因爲你在年底將所有的建議,而不是你發現拼錯的單詞是有問題的。

相反的:

for i in range(len(v)): 
    if binarySearch(f, v[i]) == True: 
     ch.append(v[i]) 
    elif binarySearch(f, v[i]) == False: 
     sugg = [] 
     for word in f: 
     if difflib.SequenceMatcher(None, v[i], word).ratio() >= 0.8: 
      sugg.append(word) 
     print(sugg) 

for j in range (len(sugg)): 
     print("if you mean ",(sugg[j]),"press",(j)) 

x=int(input()) 
ch.append(sugg[x]) 

嘗試:

for i in range(len(v)): 
    if binarySearch(f, v[i]): 
     ch.append(v[i]) 
    elif not binarySearch(f, v[i]): 
     sugg = [] 
     for word in f: 
     if difflib.SequenceMatcher(None, v[i], word).ratio() >= 0.8: 
      sugg.append(word) 
     print(sugg) 

     for j in range (len(sugg)): 
      print("if you mean ",(sugg[j]),"press",(j)) 

     x=int(input()) 
     ch.append(sugg[x])