繁体   English   中英

在python中使用字典

[英]Using dictionaries in python

我必须定义一个函数名称Correct(),该函数具有两个参数。 要测试的单词拼写错误的字符串列表(此参数将是我的文件)和我的字典(我已将其称为mydictionary)。 该函数应使用字典和check word()函数测试第一个列表中的每个单词。 正确的应该返回一个单词列表,并替换所有拼写错误的单词。 例如,正确([['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)

但是我现在收到错误'无法散列的类型:'列表'

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

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

读取文件:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM