1

我正在尝试使用 str.find() 并且它不断引发错误,我做错了什么?

import codecs

    def countLOC(inFile):
        """ Receives a file and then returns the amount
            of actual lines of code by not counting commented
            or blank lines """

        LOC = 0  
        for line in inFile:
            if line.isspace():
                continue
            comment = line.find('#')
            if comment > 0:
                for letter in range(comment):
                    if not letter.whitespace:
                        LOC += 1
                        break            
        return LOC

    if __name__ == "__main__":
        while True:
            file_loc = input("Enter the file name: ").strip()
            try:
                source = codecs.open(file_loc)
            except:
                print ("**Invalid filename**")
            else:
                break 
        LOC_count = countLOC(source)

        print ("\nThere were {0} lines of code in {1}".format(LOC_count,source.name))

错误

  File "C:\Users\Justen-san\Documents\Eclipse Workspace\countLOC\src\root\nested\linesOfCode.py", line 12, in countLOC
        comment = line.find('#')
    TypeError: expected an object with the buffer interface
4

2 回答 2

2

使用内置函数open()代替codecs.open().

您正在与非 Unicode (Python 3 bytes, Python 2 str) 和 Unicode (Python 3 str, Python 2 unicode) 字符串类型之间的区别发生冲突。Python 3 不会像 Python 2 那样在非 Unicode 和 Unicode 之间自动转换。使用不带参数的 codecs.open() 会encoding返回一个对象,bytes当您读取它时会产生该对象。

此外,您的countLOC功能将不起作用:

for letter in range(comment):
    if not letter.whitespace:
        LOC += 1
        break            

该 for 循环将遍历从零到比'#'字符串 ( letter = 0, 1, 2...) 中的位置小一的数字;whitespace不是整数方法,即使是,您也不会调用它。

此外,如果该行不包含#.

您的“固定”但在其他方面忠实(且效率低下)的版本countLOC

def countLOC(inFile):
    LOC = 0  
    for line in inFile:
        if line.isspace():
            continue
        comment = line.find('#')
        if comment > 0:
            for letter in line[:comment]:
                if not letter.isspace():
                    LOC += 1
                    break
        else:
            LOC += 1
    return LOC

我如何编写函数:

def count_LOC(in_file):
    loc = 0  
    for line in in_file:
        line = line.lstrip()
        if len(line) > 0 and not line.startswith('#'):
            loc += 1
    return loc
于 2009-05-26T05:16:39.773 回答
1

您实际上是在将打开的文件传递给函数吗?也许尝试打印类型(文件)和类型(行),因为这里有些可疑 - 以打开的文件作为参数,我无法重现您的问题!(您的代码中还有其他错误,但没有一个错误会导致该异常)。哦,顺便说一句,作为最佳实践,不要file出于自己的目的使用内置函数的名称,例如 —— 这会导致令人难以置信的混乱!

于 2009-05-26T04:17:26.060 回答