【发布时间】:2015-04-13 10:03:23
【问题描述】:
我必须定义一个函数名Correct(),它有两个参数。要测试拼写错误单词的字符串列表(此参数将是我的文件)和我的字典,我已经将其称为 mydictionary。 该函数应使用字典和检查 word() 函数测试第一个列表中的每个单词。正确应该返回所有拼写错误的单词替换的单词列表。 例如,correct(['the', 'cheif', 'stopped', 'the', 'theif']) 应该返回列表 [''the', 'chief', 'stopped', 'the', '贼'] 然后我应该在 main() 中测试函数
import string
# Makes a function to read a file, use empty {} to create an empty dict
# then reads the file by using a for loop
def make_dict():
file = open ("spellingWords.txt")
dictionary = {}
for line in file:
# Splits the lines in the file as the keys and values, and assigning them as
# misspell and spell
misspell, spell = string.split(line.strip())
# Assigns the key to the value
dictionary[misspell] = spell
file.close()
return dictionary
mydictionary = make_dict()
#print mydictionary
# Gets an input from the user
word = raw_input("Enter word")
# Uses the dictionary and the input as the parameters
def check_word(word,mydictionary):
# Uses an if statement to check to see if the misspelled word is in the
# dictionary
if word in mydictionary:
return mydictionary[word]
# If it is not in the dictionary then it will return the word
else:
return word
# Prints the function
print check_word(word,mydictionary)
def main():
file2 = open ("paragraph.txt")
file2.read()
thelist = string.split(file2)
print thelist
def correct(file2,mydictionary):
return thelist
paragraph = string.join(thelist)
print paragraph
main()
除了我的 Correct() 函数和 Main() 函数之外,我所有的其他函数都可以工作。它还给了我错误“文件对象没有属性拆分”。我的错误可以得到帮助吗?
所以我纠正了它,现在有我的主要功能
def main():
file2 = open ("paragraph.txt")
lines = file2.read()
thelist = string.split(lines)
def correct(file2,mydictionary):
while thelist in mydictionary:
return mydictionary[thelist]
paragraph = string.join(thelist)
print correct(file2,mydictionary)
但是我现在收到错误'unhashable type:'list''
【问题讨论】:
标签: python dictionary