在文件中的空行后重复循环(Python)

2024-06-26 10:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上,我有一个代码,它获取一个充满节的文本文档,用每节第一行的指令对它们进行解码,然后用它来解码后面每一行的密码。 我们的样本如下:

-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(~)内移位?这也是在使用python2.7.3


Tags: andtheto代码shiftthatlineascii
2条回答
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范围内,我会回到你的,如果不是快速回答,尝试另一个控制结构,以保持一切在正确的范围内,简单的数学应该做。在

您也可以参考这个:link

为了使其保持在范围内,您可以使用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.

相关问题 更多 >