我正在尝试使用类和函数将两个字母随机添加到字符串中
class Encryption():
def __init__(self,seed):
# Set a random seed and a self.seed attribute
self.seed = seed
# Create an empty string attribute to hold the encrypted phrase
self.encrypted_phrase = ''
# Use the string and random libraries to create two attributes
# One is the correct alphabet, another is a shuffled alphabet:
self.correct_alphabet = list(string.ascii_lowercase)
self.shuffeled_alphabet = random.sample(correct_alphabet, seed)
def encryption(self,message):
appended_message = list(message)
for let in list(range(0, len(message), 2)):
if let in self.correct_alphabet:
appended_message.append(self.shuffeled_alphabet)
return appended_message
所以,如果我这样做
e2 = Encryption(3)
e2.encryption(hello)
它失败并显示以下消息
NameError Traceback (most recent call last)
<ipython-input-24-505d8a880fb2> in <module>
----> 1 e2.encryption(message=hello)
NameError: name 'hello' is not defined
我在做什么错了?
答案 0 :(得分:1)
您的错误是使用变量而不是字符串来调用代码。查看评论或其他帖子。
您还可以使用dict简化和加速以及修复逻辑-创建一个dict进行编码,然后创建相反的dict进行解码。您可以通过字典来翻译每个字符,然后使用三元和取模来转换``.join之后仅更改每个every
字母:
import random
import string
class Encryption():
def __init__(self,seed):
# Set a random seed and a self.seed attribute
random.seed(seed)
source=string.ascii_lowercase
crypt = random.sample(source,k=len(source))
# one dict to encrypt
self.enc = {k:v for k,v in zip(source,crypt)}
# reverse crypt to decrypt
self.dec = {k:v for v,k in self.enc.items()}
def encryption(self,message,every=1):
return self.do_it(self.enc,message,every)
def decryption(self,message,every=1):
return self.do_it(self.dec,message,every)
def do_it(self, mapper, message, every):
# replace unknown characters (after lowercasing) by ?
return ''.join( (mapper.get(c,"?") if i % every == 0 else c
for i,c in enumerate(message.lower())))
测试:
crypto_1 = Encryption(42)
crypto_2 = Encryption(42)
crypto_3 = Encryption(99)
word = "apple1234juice"
code = crypto_1.encryption(word,2)
print(word,code,crypto_1.decryption(code,2),"Same crypto")
print(code,crypto_2.decryption(code,2),"Different crypto, same seed")
print(code,crypto_3.decryption(code,2),"Different crypto, other seed")
输出(重新格式化-每保留第二个字符):
p l 1?3?j i e # are kept as is
apple1234juice upllh1?3?jgiae apple1?3?juice Same crypto
upllh1?3?jgiae apple1?3?juice Different crypto, same seed
upllh1?3?jgiae gpnlf1?3?jcize Different crypto, other seed
答案 1 :(得分:0)
hello
必须是字符串,因为它不是变量。
尝试e2.encryption("hello")
或类似的方法。
因此,您的完整代码示例为:
e2 = Encryption(3)
e2.encryption("hello")