我必须编写这段代码,其中函数必须接收到文本文件的路径,文本文件必须包含仅由英文字母和标点符号组成的文本和加密数据的目标文件。标点符号必须保持不变,并且加密后的文本必须写入不同的文件。此外,我还必须验证输入。
我已经完成了大部分工作,但在第一部分中,我必须要求文本,代码不接受空格或标点符号,而据我所知,这是因为.isalpha,但是我找不到修复它的方法。
我不确定我是否完成了上述要求,所以任何类型的反馈/建设性的批评都会受到赞赏。
while True: # Validating input text
string = input("Enter the text to be encrypted: ")
if not string.isalpha():
print("Please enter a valid text")
continue
else:
break
while True: # Validating input key
key = input("Enter the key: ")
try:
key = int(key)
except ValueError:
print("Please enter a valid key: ")
continue
break
def caesarcipher(string, key): # Caesar Cipher
encrypted_string = []
new_key = key % 26
for letter in string:
encrypted_string.append(getnewletter(letter, new_key))
return ''.join(encrypted_string)
def getnewletter(letter, key):
new_letter = ord(letter) + key
return chr(new_letter) if new_letter <= 122 else chr(96 + new_letter % 122)
with open('Caesar.txt', 'a') as the_file: # Writing to a text file
the_file.write(caesarcipher(string, key))
print(caesarcipher(string, key))
print('Your text has been encrypted via Caesar-Cipher, the result is in Caesar.txt')发布于 2022-11-21 11:03:45
好吧,你可以“手动”检查一下。
# ____help_function____
def check_alpha(m_string):
list_wanted = ['!', '?', '.', ',']
for letter in m_string:
if not (letter in list_wanted or letter.isalpha()):
return False
return True
# ____in your code____
while True:
string = input("Enter the text to be encrypted: ")
if check_aplha(string):
break
else:
print('....')发布于 2022-11-21 11:03:59
您可以通过检查输入字符串是否不包含任何字母字符来验证输入字符串,然后它是无效输入:
import string
def check_valid_input(str):
for c in str:
if not c.isalpha() and (c not in string.punctuation):
return False
return True and any(c.isalpha() for c in str)
while True: # Validating input text
string = input("Enter the text to be encrypted: ")
# checking if contain only alphabet characters and punctuations
if not check_valid_input(string):
print("Please enter a valid text")
continue
else:
break这样,只有在有字母表字符且不包含任何特殊字符(除标点符号外)的情况下,才接受输入字符串。
https://stackoverflow.com/questions/74517671
复制相似问题