我如何从字符串中取出值?蟒蛇

时间:2015-02-09 12:51:47

标签: 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 (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

3 个答案:

答案 0 :(得分:1)

在这一行:

eightNumKey = (chr(random.randint(33,126)) for _ in range(8))

(a for x in y)语法创建了一个生成器。生成器是可以迭代的东西,但是随着它的发展创建迭代的每个项目。实际项目不会在该点创建,而是在访问它们时创建。

然后在打印出来时迭代生成器中的所有项目:

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。您可以将整数值存储在列表中,并在打印出来时将它们转换为字符,从而保存它们的前后转换。

答案 1 :(得分:0)

@JaimeCockburn有你问题的答案。我想展示如何使用xrangerandom.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'

ints可以重复使用。

>>> 
>>> key = random.sample(ints, 8)
>>> key
[90, 114, 93, 112, 40, 43, 95, 79]
>>> offset = sum(key)
>>> offset
666
>>> key = ''.join(map(chr, key))
>>> key
'Zr]p(+_O'
>>>

答案 2 :(得分:0)

想试试这个:

offset_factor = 0
    for i in range(0, 8):
        offset_factor = offset_factor + ord(key[i])
    offset_factor = offset_factor // 8 - 32