python中的拆分方法错误

时间:2015-12-13 23:02:33

标签: python

我正在学习python,作为练习,我正在尝试创建一个程序,根据凯撒移位密码对字符串进行编码或解码,其中密码的移位可以由用户输入。但是,当我运行它时,我收到错误:

Traceback (most recent call last):
  File "exercises.py", line 52, in <module>
    print e(input)
  File "exercises.py", line 10, in e
    slist = s.split()
AttributeError: 'builtin_function_or_method' object has no attribute 'split'.

任何人都可以帮我吗?这是代码:

import time
import string

print "Welcome to the Caesar Shift Cipher Encoder/Decoder"
time.sleep(2)
ed = raw_input("Do you want to encode or decode (e/d)? \n")
alphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',      'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')

def e(s):
    slist = s.split()

    key = {'a':'', 'b':'', 'c':'', 'd':'', 'e':'', 'f':'', 'g':'', 'h':'', 
    'i':'', 'j':'', 'k':'', 'l':'', 'm':'', 'n':'', 'o':'', 'p':'', 
    'q':'', 'r':'', 's':'', 't':'', 'u':'', 'v':'', 'w':'', 'x':'',
    'y':'', 'z':''}

    input1 = raw_input("Type what you want to encode \n")
    shift = int(raw_input("What is the shift of the cipher \n"))
    for x in key:
        if (alphabet.index(x) + shift) > 25:
            key[x] = alphabet[((alphabet.index(x)) + shift) - 26]
        else:
            key[x] = alphabet[((alphabet.index(x)) + shift)]

    for letter in slist:
        letter = key[letter]
    result = " ".join(slist)    
    return result

def d(s):
    slist = s.split()

    key = {'a':'', 'b':'', 'c':'', 'd':'', 'e':'', 'f':'', 'g':'', 'h':'', 
    'i':'', 'j':'', 'k':'', 'l':'', 'm':'', 'n':'', 'o':'', 'p':'', 
    'q':'', 'r':'', 's':'', 't':'', 'u':'', 'v':'', 'w':'', 'x':'',
    'y':'', 'z':''}

    input1 = raw_input("Type what you want to decode \n")
    shift = int(raw_input("What is the shift of the cipher \n"))
    for x in key:
        if (alphabet.index(x) - shift) > 25:
            key[x] = alphabet[((alphabet.index(x)) - shift) - 26]
        else:
            key[x] = alphabet[((alphabet.index(x)) - shift)]

    for letter in slist:
        letter = key[letter]
    result = " ".join(slist)    
    return result

if ed == "e":
    print e(input)
elif ed == "d":
    print d(input)
else:
    print "That is not an option. Please try again."
    ed = raw_input("Do you want to encode or decode (e/d)? \n")

3 个答案:

答案 0 :(得分:1)

您使用e调用您的函数dinput,这是一个内置的(并且没有字符串)。在此之前询问一个字符串,并将该字符串交给您的函数。

答案 1 :(得分:1)

您收到错误的原因是您将input传递给您的函数。 input是python中的内置函数。由于您未重新定义input,因此实际函数将传递给您的函数ed。您无法拆分内置功能。您还需要将函数传递给字符串。

看起来你甚至不需要传递任何东西给你的功能。尝试将split移至input1行之后,然后拆分input1而不是s。这比你现在想做的更有意义。

要看的另一件事是你的函数dalphabet.index(x) - shift永远不会超过25,但可能会小于0。您可能需要更改此内容。

答案 2 :(得分:-1)

您需要一个字符串来应用.split

将输入转换为如下字符串:

if ed == "e":
    print e(str(input))
elif ed == "d":
    print d(str(input))