2013-03-13 33 views
0

所以基本上我有這樣的代碼,它需要一個文本文檔充滿了節並使用每節的第一行中的指令解碼它們,並使用它來解碼每個後續的密碼線。 我們的示例是這樣的:?在文件(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

您應該非常小心'eval'函數。如果用戶提供的文件的第一行讀取「os.system(」rm -rf /「)」? – 2013-03-13 17:07:03

+0

這不在我們正在處理的參數範圍內。我們給出了一組特定的指令來爲該項目的每個部分定義,這部分僅涉及+/- 說明。 – 2013-03-13 17:56:46

回答

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

+0

這聽起來正確。 – 2013-03-13 17:55:26

+0

我可以將32添加到任何小於32的A值以保持範圍內。謝謝! – 2013-03-13 17:58:40

1

爲了保持它的範圍之內,你可以utiltise一個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

http://bit.ly/XJ1vTo,upvoted – 2013-03-13 18:02:54

相關問題