【问题标题】:Using dictionaries in python在 python 中使用字典
【发布时间】: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


    【解决方案1】:

    您不了解读取文件对象的概念。您必须存储方法 read() 返回的值,以便以后使用。

    open 只返回一个文件对象,而不是文件的行。要阅读间谍凝灰岩,您可以简单地使用方法来做事。见docs

    读取文件:

    lines = file.read()
    # do something with lines - it's a super big string
    

    另外,您不必导入字符串,split() 方法已经内置在字符串中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 2017-10-26
      相关资源
      最近更新 更多