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

时间:2013-03-13 16:40:48

标签: python python-2.7 newline

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

  

-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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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范围内,我将不得不回复你,如果不是快速回答,请尝试另一种控制结构,以便将所有内容保持在正确的范围内,简单的数学应该这样做。

您也可以参考:link