str.find()遇到问题

时间:2009-05-26 04:09:33

标签: string python-3.x text-parsing

我正在尝试使用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

2 个答案:

答案 0 :(得分:2)

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

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

此外,您的countLOC功能无效:

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

for循环将遍历从0到1的数字,小于字符串'#'letter = 0, 1, 2...的位置; whitespace不是整数的方法,即使它是,你也不是在调用它。

此外,如果该行不包含#,则永远不会递增LOC。

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

答案 1 :(得分:1)

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

相关问题