2014-10-18 4 views
0

내 프로그램에서 사용자에게 P6 .ppm 이미지의 파일 이름을 입력하도록 요청하면 내 프로그램이 새로운 파일을 그레이 스케일로 변환하는 P5 .pgm 이미지로 씁니다. 열려있는 이미지에 헤더에 주석이있는 경우를 제외하고는 프로그램이 완벽하게 작동합니다. 내 문제가 내 Main() 또는 GetNum 기능에 있는지 확신 할 수 없습니다. 어떤 도움을 많이 주시면 감사하겠습니다!Python : .ppm 파일을 여는 동안 주석을 건너 뛸 필요가 있음

fileInput = raw_input("Enter the name of the original file including .ppm at the end: ")#P6 = .ppm 
fileOutput = raw_input("Enter the file name for the new picture including .pgm at the end: ")#P5 = .pgm 
readFile = open(fileInput, "rb") 
writeFile = open(fileOutput, 'wb') 
magicNumber1 = readFile.read(1)#MagicNumber 1 and 2 grabs the first two bytes for the header, which should be P6 
magicNumber2 = readFile.read(1) 

또는 내 문제는 내 GetNum 기능에 존재처럼 내 주요 외모의 시작?

DEF GetNum (F)는 :

currentChar = f.read(1) #Reads through the file 1 byte at a time 

while currentChar.isdigit() == False: 
    while currentChar.isspace(): #Keep reading if the current character is a space 
     currentChar = f.read(1) 

    if currentChar == "#": #If a comment or new line keep reading 
     while currentChar != "\n": 
      currentChar = f.read(1) 

num = currentChar 
while currentChar.isdigit(): #If current character is a digit, add it onto Num 
    currentChar = f.read(1) 
    num = num + currentChar 

num = num.strip() 

return num 

답변

0

문제 GetNum(f)으로한다. 이 루프

while currentChar != "\n": 
    currentChar = f.read(1) 

currentChar의 끝에서

num = currentChar 세트 \n

-num을 의미 \n

같다 그리고 currentChar 때문에 \n에게 결코 입력하지됩니다 다음 루프 while currentChar.isdigit()가 포함되어 있습니다. 따라서 num에는 숫자가 추가되지 않으며 num = num.strip()은 포함 된 \n을 제거하므로 GetNum(f)은 빈 문자열을 반환합니다.

...

당신이 PPM 파일을 직접 분석보다는 라이브러리를 사용하는 어떤 이유가 있나요? 나는 이것이 ppmtopgm이 존재한다고 가정 할 때 프로그래밍 연습이라고 가정합니다.

FWIW, 나는 종종 NetPBM 파일을 사용하고, C에서는 필자 자신의 파서를 사용하지만 파이썬에서는 일반적으로 라이브러리를 사용하여 읽습니다. 때로는 라이브러리를 사용하여 파일을 작성하지만 파일 형식이 너무 단순하기 때문에 종종 "손으로"수행합니다.

구문 분석 문제에 접근하는 좋은 방법은 state machine을 사용하는 것입니다.

파이썬 모듈 shlex가 이와 같은 일을하는 데 사용될 수 있다고 언급해야하지만, 이것이 프로그래밍 연습이라면 shlex를 사용하지 않아야합니다. :)