Python 将字符串编码为破折号分隔的数字,将破折号分隔的数字解码为字符串
任务:编写一个程序,让用户选择编码或 解码您可以将字母编码为以空格分隔的数字 破折号,或将一系列数字(也用破折号分隔)解码为 信件 我正在学习python,这个实验室被证明是非常困难的,因为我还不知道使它运行所需的所有工具。我设法让编码部分工作,但我的解码部分是垃圾。我认为这是把两位数字当作单独的数字处理(“19”表示“1”和“9”,所以返回“ai”而不是“s”)。我曾考虑过从使用索引转换为使用chr()将数字转换为字母,但我也不熟悉这一点,在尝试添加96以获得正确的数字时,我不断遇到类型错误。 然后,encode_letters函数有点笨拙,但它可以工作。然而,decode_numbers函数正是我所需要的 谁能告诉我我做错了什么Python 将字符串编码为破折号分隔的数字,将破折号分隔的数字解码为字符串,python,python-3.x,Python,Python 3.x,任务:编写一个程序,让用户选择编码或 解码您可以将字母编码为以空格分隔的数字 破折号,或将一系列数字(也用破折号分隔)解码为 信件 我正在学习python,这个实验室被证明是非常困难的,因为我还不知道使它运行所需的所有工具。我设法让编码部分工作,但我的解码部分是垃圾。我认为这是把两位数字当作单独的数字处理(“19”表示“1”和“9”,所以返回“ai”而不是“s”)。我曾考虑过从使用索引转换为使用chr()将数字转换为字母,但我也不熟悉这一点,在尝试添加96以获得正确的数字时,我不断遇到类型错误。
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())
def encode_字母():
全局代码输出
加密密钥=('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(输入(“输入要编码的消息:\n”))
msg_in=msg_in.lower()
from_index=0
to_指数=1
对于msg_中的i:
字母_found=False
对于加密中的e\u密钥:
如果('a',我认为如果您跟踪类型转换,您可以将其简化很多:
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
将整数转换回字符串。这使我们可以将字符串转换为以连字符分隔的整数序列,然后使用字典将该序列转换回输入字符串,从而使加密和描述更容易。例如cea萨尔·奇弗尔:
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
0-1-2-3-4-5-6
b-c-d-e-f-B-A-D-E-F
使用的字典如下所示:
{'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]+偏移量)%26]
查找属于某个字符的“数字”,添加偏移量,使用模26将z+1
转换为a
,而不是错误。然后is根据其数字查找正确的“新”字符
您可以对任务执行相同的操作-您只需要将字符
映射到数字
和数字
映射到字符
解码时,在'-'
处拆分字符串,并获取数字值的字符-编码时,检查单词的所有字符并从dict中获取正确的数字,然后'-'。将它们连接起来()
适用于您的任务:
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"))
输出:
bcdefgh # encode abcdefg , +1
bcdefgh # decode abcdefg , -1
abrakadabrazzz # endoce + decode
0-1-2-3-4-5-6
b-c-d-e-f-B-A-D-E-F
为什么不使用字典作为查找?出现类型错误可能是因为您试图将整数添加到字符串中。而在某些语言中(如JavaScript)可以这样做,在Python中不能这样做——在Python中,我们需要将一个整数转换为字符串,然后将其添加到字符串中+'s'
没有。我的教授在上节课上曾简要地提到过词典,我认为这可能是处理这个问题的一个好方法。我将寻找有关创建和使用词典的指导。谢谢。