2012-11-27 54 views
-5

我需要創建一個讀取文本文件並創建拼寫錯誤的單詞的字典的函數。 這是我迄今爲止我如何完成我的拼寫檢查代碼?

def spellCheck(textFileName): 

    file=open("words.txt","r") 
    wordsList = file.read() 
    print wordsList 
    file.close() 

    file=open(textFileName, "r") 
    wordsToCheck = file.read() 
    print wordsToCheck 
    file.close() 

    # The next line creates the dictionary 
    # This dictionary will have the word that has been spelt wrong as the key and the number of times it has been spelt wrong as the value 
    spellingErrors = dict= {'words', wordsToCheck} 

,我需要:

# Loop through the wordsToCheck list 
# Change the current word into lower case 
# If the current word does not exist in the wordsList then 
     # Check if the word already exists in the spellingErrors dictionary 
       # If it does not exist than add it to the dictionary with the initial value of 1. 
       # If it does exist in the dictionary then increase the value by 1 

# Return the dictionary 
+1

所以,實際的算法,到目前爲止你嘗試過了什麼? – learner

+0

本地化太大。再次。 http://stackoverflow.com/questions/13573552/can-anyone-help-me-with-my-spell-check-code – Yandros

回答

1

這是非常簡單的,而且會極其緩慢:

wordsList = wordsList.lower().split() 
for word in wordsToCheck.lower().split(): 
    if not word in wordsList: 
     if word not in spellingErrors: 
      spellingErrors[word]=0 
     spellingErrors[word] += 1 
+0

我得到這個錯誤,當我運行這個 回溯(最近呼叫最後): 文件「 」,第1行,在 拼寫檢查( 「test1.txt的」) 文件 「j:\蟒\拼寫檢查(1)py」 爲48行,在拼寫檢查 spellingErrors [字] = 0 類型錯誤:「設置'對象不支持項目分配 – user1839493

1
# load the dictonary 
dict_text = open('words.txt','r').read().split() 
# convert dictionary to lowercase set() for easy access 
dictionary = set([i.lower() for i in dict_text]) 

# load a text 
words_to_check = open(text_file_name, 'r').read().split() 
# and check it 
for word in words_to_check : 
    if word.lower() not in dictionary : 
     print 'misspelled:', word