如何从字符串中提取值?python
我的任务是创建一个偏移因子,该因子基于在程序前面计算的八个字符的键。首先,需要将八个字符键中的每个字符转换为等效的ascii数字,然后相加,然后将结果除以8,然后四舍五入为整数。最后,需要从该值中减去32 这是偏移因子之前的代码:如何从字符串中提取值?python,python,string,Python,String,我的任务是创建一个偏移因子,该因子基于在程序前面计算的八个字符的键。首先,需要将八个字符键中的每个字符转换为等效的ascii数字,然后相加,然后将结果除以8,然后四舍五入为整数。最后,需要从该值中减去32 这是偏移因子之前的代码: def EncryptCode(): userFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n") with open (u
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
此程序有三种选择。
1.加密消息。
2.解密消息。
3.退出程序。
做出选择:1
以“.txt”结尾命名要加载的文件和目录:
Sample.txt
将被加密的代码:
在拉曼查的某个地方,在一个我不记得名字的地方,不久前住着一位绅士,他有一把长矛和一块古老的盾牌放在架子上,养着一匹瘦瘦的马和一只赛狗。
八字符键:txJ#K#P`
回溯(最近一次呼叫最后一次):
文件“N:\Computer Science\Course Work\Controlled assessment\Controlled assessment.py”,第54行,在
showMenu()
文件“N:\Computer Science\Course Work\Controlled assessment\Controlled assessment.py”,第38行,在showMenu中
EncryptCode()
文件“N:\Computer Science\Course Work\Controlled assessment\Controlled assessment.py”,第26行,加密代码
偏置因子=偏置因子+ord(八键)
TypeError:ord()应为长度为1的字符串,但找到生成器
在这一行:
eightNumKey = (chr(random.randint(33,126)) for _ in range(8))
(a代表y中的x)
语法创建一个生成器。生成器是可以迭代的东西,但会在迭代过程中创建每个项。实际项目不是在该点创建的,而是在访问时创建的
然后,在输出生成器中的所有项目时,迭代这些项目:
print('\nEight-Character Key:', "".join(eightNumKey))
在这一行之后,生成器是空的,您再也无法取回这些项目
最后,您尝试获取该生成器的序数值,这没有任何意义:
offsetFactor = offsetFactor + ord(eightNumKey) # eightNumKey is a generator
解决方案 实际上,你想要的是更像这样的东西:
# Create a list, not a generator
eightNumKey = [chr(random.randint(33, 126)) for _ in range(8)]
# Iterate the list to print them out
print('\nEight-Character Key:', "".join(eightNumKey))
# Iterate the list again to sum the ordinal values
offsetFactor = sum(ord(c) for c in eightNumKey)
...
更新:
正如一位评论者所提到的,您实际上是在执行
ord(chr(random_number))
,这有点多余,因为最终结果只是再次执行random_number
。您只需将整数值存储在列表中,并在打印时将其转换为字符,保存前后转换。@JaimeCockburn可以回答您的问题。我想展示如何使用xrange
和random.sample
重构代码,避免将数字转换为字符串,然后再转换回数字
>>>
>>> ints = xrange(33, 127)
>>> key = random.sample(ints, 8)
>>> key
[78, 75, 77, 73, 94, 60, 44, 67]
>>> offset = sum(key)
>>> offset
568
>>> key = ''.join(map(chr, key))
>>> key
'NKMI^<,C'
想试试这个:
offset_factor = 0
for i in range(0, 8):
offset_factor = offset_factor + ord(key[i])
offset_factor = offset_factor // 8 - 32
你想做什么还不清楚。eightNumKey是一个字符序列,您显然知道它,因为您以前在它上面使用过
join
。您希望ord()
如何处理该序列?另外,我不明白为什么要通过调用int上的chr()
来构造序列,然后立即要调用int上的ord()
。您可能需要证明ord(chr(n))
等于n
。
offset_factor = 0
for i in range(0, 8):
offset_factor = offset_factor + ord(key[i])
offset_factor = offset_factor // 8 - 32