文本串加密和解密: 一个文本串可用事先给定的字母映射表进行加密。例如:设字母映射表为: a b c d e f j h I j k l m n o p q r s t u v w x y z n g z q t c o b m u h e l k p d a w x f y I v r s j 则字符串”encrypt”被加密为”tkzwsd”。编写一个程序exp4-2.py,将输入的文本串加密后输出,然后进行解密并输出。
时间: 2023-11-28 08:49:41 浏览: 182
加密程序:
```python
def encrypt(text, mapping):
# 构建映射表
map_dict = {}
for i in range(len(mapping)):
map_dict[mapping[i]] = chr(ord('a') + i)
# 加密文本串
res = ''
for c in text:
if c in map_dict:
res += map_dict[c]
else:
res += c
return res
```
解密程序:
```python
def decrypt(text, mapping):
# 构建映射表
map_dict = {}
for i in range(len(mapping)):
map_dict[chr(ord('a') + i)] = mapping[i]
# 解密文本串
res = ''
for c in text:
if c in map_dict:
res += map_dict[c]
else:
res += c
return res
```
完整代码如下:
```python
def encrypt(text, mapping):
# 构建映射表
map_dict = {}
for i in range(len(mapping)):
map_dict[mapping[i]] = chr(ord('a') + i)
# 加密文本串
res = ''
for c in text:
if c in map_dict:
res += map_dict[c]
else:
res += c
return res
def decrypt(text, mapping):
# 构建映射表
map_dict = {}
for i in range(len(mapping)):
map_dict[chr(ord('a') + i)] = mapping[i]
# 解密文本串
res = ''
for c in text:
if c in map_dict:
res += map_dict[c]
else:
res += c
return res
if __name__ == '__main__':
mapping = 'ngzqtcobmuhelkpdawxfyivrsj'
text = input('请输入要加密的文本串:')
encrypted = encrypt(text, mapping)
print('加密后的文本串为:', encrypted)
decrypted = decrypt(encrypted, mapping)
print('解密后的文本串为:', decrypted)
```
示例输入和输出:
```
请输入要加密的文本串:encrypt
加密后的文本串为:tkzwsd
解密后的文本串为:encrypt
```
阅读全文