Моя задача - создать коэффициент смещения, который основан на восьмисимвольном ключе, который вычисляется ранее в программе. во-первых, каждый из символов в восьмисимвольном ключе необходимо преобразовать в эквивалентные числа ascii, затем добавить вместе, а затем делить этот результат на 8, а затем округлить до целого числа. наконец, 32 следует вычесть из этого значения.Как извлечь значения из строки? Python
это мой код до смещения фактора:
def EncryptCode():
userFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
with open (userFileLoad,mode="r",encoding="utf=8") as encrypt_file:
encrypt = encrypt_file.read()
print ("Code that will be encrypted:")
printMessage(encrypt)
eightNumKey = (chr(random.randint(33,126)) for _ in range(8))
print('\nEight-Character Key:', "".join(eightNumKey))
Это, как я пытался реализовать смещение фактора в программе:
def EncryptCode():
userFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
with open (userFileLoad,mode="r",encoding="utf=8") as encrypt_file:
encrypt = encrypt_file.read()
print ("Code that will be encrypted:")
printMessage(encrypt)
offsetFactor = 0
eightNumKey = (chr(random.randint(33,126)) for _ in range(8))
print('\nEight-Character Key:', "".join(eightNumKey))
offsetFactor = offsetFactor + ord(eightNumKey) #I need help with this bit
offsetFactor = offsetFactor/8
offsetFactor = math.floor(offsetFactor)
offsetFactor = offsetFactor - 32
text = encrypt.split()
print("The offset Factor is:",offsetFactor)
это то, что мой выход показывает:
This program has three choices.
1. Encrypt a message.
2. Decrypt the message.
3. Exit the program.
Make your choice: 1
Name the file and directory you want to load with the ending '.txt':
Sample.txt
Code that will be encrypted:
Somewhere in la Mancha, in a place whose name I do not care to remember, a gentleman lived not long ago, one of those who has a lance and ancient shield on a shelf and keeps a skinny nag and a greyhound for racing.
Eight-Character Key: txJ#K_P`
Traceback (most recent call last):
File "N:\Computer Science\Course Work\Controlled assessment\Controlled Assessment.py", line 54, in <module>
showMenu()
File "N:\Computer Science\Course Work\Controlled assessment\Controlled Assessment.py", line 38, in showMenu
EncryptCode()
File "N:\Computer Science\Course Work\Controlled assessment\Controlled Assessment.py", line 26, in EncryptCode
offsetFactor = offsetFactor + ord(eightNumKey)
TypeError: ord() expected string of length 1, but generator found
Это не ясно, что вы хотите сделать.eightNumKey - это последовательность символов, которую вы, очевидно, знаете, потому что раньше вы использовали 'join'. Что вы ожидаете от 'ord()', чтобы сделать с этой последовательностью? Кроме того, я не понимаю, почему вы создаете последовательность, вызывая 'chr()' на int, а затем сразу же хотите называть 'ord()' на ней. –
Возможный дубликат [Извлечение значений из строки] (http://stackoverflow.com/questions/2093812/extracting-values-from-a-string) –