将字符串编码为用破折号分隔的数字,将数字破折号解码为字符串

时间:2018-11-18 19:17:33

标签: python python-3.x

  

任务:编写程序,使用户可以选择编码或   解码。您可以将字母编码为数字,并用   破折号,或将一系列数字(也用破折号分隔)解码为   字母。

我正在学习python,事实证明该实验室非常困难,因为我尚不知道实现该功能所需的所有工具。我设法使编码部分正常工作,但是我的解码部分却很糟糕。我认为它采用2位数字并将其视为单个数字(“ 19”分别为“ 1”和“ 9”,因此返回“ ai”而不是“ s”)。我曾考虑过从使用索引转换为尝试使用chr()将数字转换为字母,但是我也不熟悉,在尝试加96以获得正确数字时,我总是遇到类型错误。 然后encode_letters函数有点笨拙,但是可以工作。但是,decode_numbers函数确实适合我。

有人可以告诉我我在做什么错吗?

def encode_letters():
    global code_out
    encryption_key = (('a','1'), ('b','2'), ('c','3'), ('d','4'), ('e','5'), ('f','6'), ('g', '7'), ('h','8'), ('i','9'), ('j','10'), ('k','11'), ('l','12'),
        ('m','13'), ('n','14'), ('o','15'), ('p','16'), ('q','17'), ('r','18'), ('s','19'), ('t','20'), ('u','21'), ('v','22'), ('w','23'), ('x','24'),
        ('y','25'), ('z','26'))
    msg_in = str(input("Enter the message you wish to encode:\n"))
    msg_in = msg_in.lower()
    from_index = 0
    to_index = 1
    for i in msg_in:
        letter_found = False
        for e in encryption_key:
            if ('a' <= i and i <= 'z') and i == e[from_index]:
                code_out = code_out + e[to_index] + "-"
                letter_found = True
        if not letter_found:
            code_out = code_out + i

    return code_out

def return_encoded():
    global code_out
    code_out = code_out.rstrip("-")
    print("Your secret code is:", code_out.replace('- ', ' '))

def decode_numbers():
    global string_out
    encryption_key = (('a','1'), ('b','2'), ('c','3'), ('d','4'), ('e','5'), ('f','6'), ('g','7'), ('h','8'), ('i','9'), ('j','10'), ('k','11'), ('l','12'),
        ('m','13'), ('n','14'), ('o','15'), ('p','16'), ('q','17'), ('r','18'), ('s','19'), ('t','20'), ('u','21'), ('v','22'), ('w','23'), ('x','24'),
        ('y','25'), ('z','26'))
    numbers_in = input("Enter the numbers separated by dashes that you wish to decode: ")
    numbers_in = numbers_in.replace('-', ' ')
    print(numbers_in)
    from_index = 1
    to_index = 0

    for i in numbers_in:
        number_found = False
        for e in encryption_key:
            if i == e[from_index]:
                string_out = string_out + e[to_index]
                number_found = True
        if not number_found:
            string_out = string_out + i
    return string_out

def return_decoded():
    global string_out
    print("Your decoded string is: ", string_out.capitalize())

2 个答案:

答案 0 :(得分:1)

如果您跟踪类型转换,我认为您可以简化很多操作

def convert(s, method='encode'):
  if method == 'encode':
    return '-'.join([str(ord(i)) for i in s])
  elif method == 'decode':
    return ''.join([str(chr(int(i))) for i in s.split('-')])

s = 'cats on wheels'
encoded = convert(s, method='encode')
decoded = convert(encoded, method='decode')

print(encoded) # prints 99-97-116-115-32-111-110-32-119-104-101-101-108-115
print(decoded) # prints cats on wheels

正如您所说,可以使用ord将字符串转换为整数,然后使用chr将整数转换回字符串。这样,我们就可以将字符串翻转为连字符分隔的整数序列,然后将其翻转回输入字符串

答案 1 :(得分:0)

使用字典可使加密和解密变得更加容易。撒腹泻的例子:

d = {}
# build the encode/decode dict
for k in range(26):
    cha = chr(ord("a")+k)
    d[cha] = k
    d[cha.upper()] = k
    d[k] = cha

print(d)

def encode(word,offset):
    # dont use other things then a-zA-Z or else...
    return ''.join(d[ (d[c]+offset)%26 ] for c in word)

def decode(word,offset):
    return encode(word,-offset)

print(encode("abcdefg",1))
print(decode("abcdefg",-1))

print ( encode(decode("abrakadabrazzz",1),1) )

输出:

bcdefgh  # encode abcdefg , +1
bcdefgh  # decode abcdefg , -1
abrakadabrazzz # endoce + decode

使用的字典如下:

{'a': 0, 'A': 0, 0: 'a',     'b': 1, 'B': 1, 1: 'b',     'c': 2, 'C': 2, 2: 'c', 
 'd': 3, 'D': 3, 3: 'd',     'e': 4, 'E': 4, 4: 'e',     'f': 5, 'F': 5, 5: 'f', 
 'g': 6, 'G': 6, 6: 'g',     'h': 7, 'H': 7, 7: 'h',     ...,  
 'x': 23, 'X': 23, 23: 'x',  'y': 24, 'Y': 24, 24: 'y',  'z': 25, 'Z': 25, 25: 'z'}

基本上,它将任何小写和大写字母映射到一个数字,然后将数字映射回小写字符。

编码d[ (d[c]+offset)%26 ]查找属于字符的“数字”,添加偏移量,使用模26将z+1转换为a而不是错误。然后是按数字查找正确的“新”字符。

您可以为自己的任务做同样的事情-您只需将character映射到number,将number映射到character

解码时,将字符串在'-'处分割,并获取您获得的numbervalue的字符-编码时,遍历单词的所有字符并从字典中获取正确的数字,然后'-'.join()


适用于您的任务:

from string import ascii_lowercase as low  # "abc..xyz"

d = {}
number_for_a = ord("a") 
# add the letters/numbers - upper case are 100 + lower case number
for k in low:
    d[k]         = str(ord(k) - number_for_a)       
    d[k.upper()] = str(100 + ord(k) - number_for_a)  
# add the reverse mapping number to character
for k,v in list(d.items()):
    d[v] = k

def encode(word):    
    # word for both cases - if no `-` in word its iterated character wise, else
    # the word is split at '-' and any splits are put through the dictionary 
    if '-' in word:
        return '-'.join(d[c] for c in word.split("-"))
    return '-'.join(d[c] for c in word)

def decode(phrase):
    return encode(phrase)

print(encode("abcdefg"))
print(decode("1-2-3-4-5-101-100-103-104-105"))

输出:

0-1-2-3-4-5-6
b-c-d-e-f-B-A-D-E-F