我怎样才能完成拼写检查代码?

时间:2012-11-27 17:14:26

标签: python dictionary python-2.7

我需要创建一个读取文本文件的函数,并创建拼写错误的单词的字典。 这就是我到目前为止所拥有的

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

2 个答案:

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

答案 1 :(得分: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
相关问题