0

所以基本上我有这个代码,它获取一个充满节的文本文档,并使用每个节的第一行中的指令对其进行解码,并使用它来解码每个后续行中的密码。我们的示例如下所示:

-25+122-76
?ST^jT^jLj_P^_jZQj_SPjTY[`_jQTWPx ?ST^jT^j_SPj^PNZYOjWTYPx

+123+12+1234
0A:MXPBEEXA:II>GXGHPw

这是通过将第一行中的整数相加并将每个 ASCII 字符移动这么多来破译的。到目前为止,我的代码如下所示:

#Here I define the Shift function that will take a character, convert it to its ASCII numeric value, add N to it and return the ASCII character.

def Shift(char, N):
    A = ord(char)
    A += N
    A = chr(A)
    return A

#Here's the code I have that opens and reads a file's first line as instructions, evaluates the numeric value of that first line, throws rest into a list and runs the Shift helper function to eval the ASCII characters.
def driver(filename):
    file = open(filename)
    line = file.readline()
    file = file.readlines()
    N = eval(line)
    codeList = list(file)  
    for char in codeList:  
        newChar = Shift(char, N)  
        codeList[char] = codeList[newChar]  
    print str(codeList)  

现在我的问题是如何在节中的每个空白行之后重复我的代码?另外,如何让字符仅在 ASCII 范围 32(空格)和 126(~)内移动?这也是使用 Python 2.7.3

4

2 回答 2

1

为了将其保持在范围内,您可以使用 a deque,我也会eval先手动将数字转换为整数,然后使用转换表来解码数据,例如:

data = """-25+122-76
?ST^jT^jLj_P^_jZQj_SPjTY[`_jQTWPx ?ST^jT^j_SPj^PNZYOjWTYPx"""

lines = data.splitlines()

import re
from collections import deque
from string import maketrans

# Insted of using `eval` - find number with signs and sum
shift = sum(int(i) for i in re.findall('[-+]\d+', lines[0]))
# Explicit range of characters
base_set = map(chr, range(32, 127))
# Create a new deque which can be rotated and rotate by shift
d = deque(base_set)
d.rotate(-shift)
# Make translation table and translate
t = maketrans(''.join(base_set), ''.join(d))
print lines[1].translate(t)
# This is a test of the input file.5This is the second line.
于 2013-03-13T18:00:02.227 回答
0
file = open(filename)
while True:
    line = file.readline()
    if not line:      # if end of file, exit
        print "Reached end of file"
        break
    if line == "\n":  # if new line, or empty line, continue
        continue
    else:
        your function

至于将所有内容保持在 ASCII 范围内,我将不得不回复您,如果不是快速回答,请尝试另一种控制结构以将所有内容保持在正确的范围内,简单的数学应该做。

你也可以参考这个: 链接

于 2013-03-13T17:44:08.713 回答