微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我不能让这段代码运行我不断收到类型错误:“方法”对象不可下标

如何解决为什么我不能让这段代码运行我不断收到类型错误:“方法”对象不可下标

我不断收到此代码错误代码,但我不知道为什么...它一直告诉我无论我做什么,方法对象都不可下标.. 任何帮助表示赞赏。我也知道我的代码可能不漂亮。我还在学习Python。从字面上看,我所做的几乎所有事情都会收到错误代码,但我不知道如何修复它。我几乎尝试了所有我能想到的。

import string


def load_words(file_name):
    '''
    file_name (string): the name of the file containing 
    the list of words to load    
    
    Returns: a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list,this function may
    take a while to finish.
    '''
    print('Loading word list from file...')
    
    file = open(file_name,'r')
    line = file.readline()
    word_list = line.split()
    
    print('  ',len(word_list),'words loaded.') #word_list is the list of valid words 
    file.close()
    return word_list

def is_word(word_list,word):
    '''
    Determines if word is a valid word,ignoring
    capitalization and punctuation (" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")

    word_list (list): list of words in the dictionary.
    word (string): a possible word.
    
    Returns: True if word is in word_list,False otherwise

    Example:
    >>> is_word(word_list,'bat') returns
    True
    >>> is_word(word_list,'asdf') returns
    False
    '''
    
    word = word.lower
    word = word.strip("!@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list


def get_story_string():
    """
    Returns: a joke in encrypted text.
    """
    f = open("story.txt","r")
    story = str(f.read())
    f.close()
    return story

WORDLIST_FILENAME = 'words.txt'

class Message(object):
    def __init__(self,text):
        '''
        Initializes a Message object
                
        text (string): the message's text

        a Message object has two attributes:
            self.message_text (string,determined by input text)
            self.valid_words (list,determined using helper function load_words
        '''
        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)

    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class
        
        Returns: self.message_text
        '''
        return self.message_text


    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class
        
        Returns: a copY of self.valid_words
        '''
        return self.get_valid_words[:]
    

    def build_shift_dict(self,shift):
        '''
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to a
        character shifted down the alphabet by the input shift. The dictionary
        should have 52 keys of all the uppercase letters and all the lowercase
        letters only.        
        
        shift (integer): the amount by which to shift every letter of the 
        alphabet. 0 <= shift < 26

        Returns: a dictionary mapping a letter (string) to 
                 another letter (string). 
        '''
        lower = list(string.ascii_lowercase)
        lower_values = list(string.ascii_lowercase)
        shift_lower_values = lower_values[shift:] + lower_values[:shift]
        
        upper = list(string.ascii_uppercase)                 
        upper_values = list(string.ascii_uppercase)
        upper_shift_values = upper_values[shift:] + upper_values[:shift]

        full_keys = lower + upper
        full_values = shift_lower_values + upper_shift_values

        self.shift_dict = dict(zip(full_keys,full_values))
        return self.shift_dict        



    def apply_shift(self,shift):
        '''
        Applies the Caesar Cipher to self.message_text with the input shift.
        Creates a new string that is self.message_text shifted down the
        alphabet by some number of characters determined by the input shift        
        
        shift (integer): the shift with which to encrypt the message.
        0 <= shift < 26

        Returns: the message text (string) in which every character is shifted
             down the alphabet by the input shift
        '''
        message = self.get_message_text()       
        new_string = ""                         
        shiftDictonary = self.build_shift_dict(shift)       
        for letter in message:                  
            if letter in shiftDictonary:
                new_string += shiftDictonary[letter]
            else:
                new_string += letter
        return new_string

class PlaintextMessage(Message):
 
    def __init__(self,text,shift):
        '''
        Initializes a PlaintextMessage object        
        
        text (string): the message's text
        shift (integer): the shift associated with this message

        A PlaintextMessage object inherits from Message and has five attributes:
            self.message_text (string,determined using helper function load_words)
            self.shift (integer,determined by input shift)
            self.encrypting_dict (dictionary,built using shift)
            self.message_text_encrypted (string,created using shift)

        Hint: consider using the parent class constructor so less 
        code is repeated
        '''
        Message.__init__(self,text)
        self.shift = shift
        self.encrypting_dict = self.build_shift_dict(shift)
        self.message_text_encrypted = self.apply_shift(shift)

    def get_shift(self):
        '''
        Used to safely access self.shift outside of the class
        
        Returns: self.shift
        '''
        return self.shift

    def get_encrypting_dict(self):
        '''
        Used to safely access a copy self.encrypting_dict outside of the class
        
        Returns: a copY of self.encrypting_dict
        '''
        return self.encrypting_dict.copy()


    def get_message_text_encrypted(self):
        '''
        Used to safely access self.message_text_encrypted outside of the class
        
        Returns: self.message_text_encrypted
        '''
        return self.message_text_encrypted
    
    
    def change_shift(self,shift):
        '''
        Changes self.shift of the PlaintextMessage and updates other 
        attributes determined by shift (ie. self.encrypting_dict and 
        message_text_encrypted).
        
        shift (integer): the new shift that should be associated with this message.
        0 <= shift < 26

        Returns: nothing
        '''
        self.__init__(self.message_text,shift)

class CiphertextMessage(Message):
  def __init__(self,text):
       
       Message.__init__(self,text)
     
  def decrypt_message(self):
   best_shift = None
   best_real_words = 0
   best_msg = ""

   for s in range(26):
       decrypted_text = self.apply_shift(s)
       words = decrypted_text.split()
       real_words = sum([is_word(self.get_valid_words(),w) for w in words])
       if real_words > best_real_words:
          best_shift = s
          best_real_words = real_words
          best_msg = decrypted_text

   return (best_shift,best_msg)
   

#Example test case (PlaintextMessage)
plaintext = PlaintextMessage('hello',2)
print('Expected Output: jgnnq')
print('Actual Output:',plaintext.get_message_text_encrypted())
    
#Example test case (CiphertextMessage) 
#Uncomment the following lines when you have completed your CiphertextMessage class
ciphertext = CiphertextMessage('jgnnq')
print('Expected Output:',(24,'hello'))
print('Actual Output:',ciphertext.decrypt_message())

解决方法

问题出在这一行:

word = word.lower

您给 word 一个方法的引用,该方法会传播到您之后使用 word 的所有内容。你可能想写这个:

word = word.lower()

考虑type hinting,因为它可以让您的 IDE 轻松捕获此类错误。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。