我必须定义一个函数名称Correct(),它有两个参数。要测试拼写错误的单词的字符串列表(此参数将是我的文件),以及我已经创建的字典,称为mydictionary。 该函数应使用字典和check word()函数测试第一个列表中的每个单词。正确应该返回一个单词列表,替换所有拼写错误的单词。 例如,正确(['the','cheif','stopped','the','theif'])应该返回列表['''','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)
但是我现在收到错误'不可用的类型:' list''
答案 0 :(得分:1)
您不了解读取文件对象的概念。您必须存储方法read()
返回的值,以便以后可以使用它。
open
只返回一个文件对象,而不是文件的行。要阅读间谍凝灰岩,您可以简单地使用方法来做事。请参阅docs
要阅读文件:
lines = file.read()
# do something with lines - it's a super big string
此外,您不必导入字符串,split()
方法已内置字符串。