【问题标题】:Python: Need to skip comments while opening a .ppm filePython:打开 .ppm 文件时需要跳过注释
【发布时间】:2014-10-18 22:24:21
【问题描述】:

我的程序要求用户输入 P6 .ppm 图像的文件名,然后我的程序将新文件作为 P5 .pgm 图像写入并将其转换为灰度。 我的程序运行良好,除非正在打开的图像在标题中有 cmets。我不确定我的问题是在我的 Main() 还是 GetNum 函数中。非常感谢任何帮助!

我的 main 开头是这样的

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

【问题讨论】:

    标签: python header comments grayscale ppm


    【解决方案1】:

    问题在于GetNum(f)

    循环结束

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

    currentChar 等于 \n

    这意味着num = currentCharnum 设置为\n

    因为currentChar 包含\n 下一个循环while currentChar.isdigit() 永远不会进入。所以num 没有添加任何数字,num = num.strip() 去掉了它包含的\n,所以GetNum(f) 返回一个空字符串。

    ...

    您是否有任何理由自己解析 PPM 文件,而不是使用库?鉴于 ppmtopgm 存在,我假设这是一个编程练习。

    FWIW,我经常使用 NetPBM 文件,在 C 语言中我使用自己的解析器,但在 Python 中我通常使用库来读取它们;有时我使用库来编写它们,但文件格式非常简单,我经常“手工”完成。

    解决解析问题的一个好方法是使用state machine

    我还应该提到 Python 模块 shlex 可以用来做这样的事情,但我想如果这是一个编程练习,你可能不应该使用 shlex。 :)

    【讨论】:

      猜你喜欢
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 2012-12-18
      相关资源
      最近更新 更多