在文件中遇到空行后重新迭代循环(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(波浪号)之间?另外,我使用的是Python 2.7.3。
2 个回答
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.
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范围内,我需要再想想。如果没有快速的答案,可以尝试使用其他控制结构来确保所有内容都在正确的范围内,简单的数学运算应该就能解决这个问题。
你也可以参考这个: 链接