문제

나는 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
도움이 되었습니까?

해결책

내장 기능을 사용하십시오 open() 대신에 codecs.open().

비 니코 코드 (Python 3 bytes, 파이썬 2 str) 및 유니 코드 (파이썬 3 str, 파이썬 2 unicode) 문자열 유형. Python 3은 Python 2 Will과 같은 비 유니 코드와 유니 코드 사이에서 자동으로 변환되지 않습니다. Codecs.open ()을 사용하지 않고 사용합니다 encoding 매개 변수는 생성되는 객체를 반환합니다 bytes 당신이 그것을 읽을 때.

또한, 당신의 countLOC 기능은 작동하지 않습니다.

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

루프를 위해 '#' 문자열에서 (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

다른 팁

실제로 열린 파일을 함수에 전달하고 있습니까? 여기에 비린내가있는 것이기 때문에 인쇄 유형 (파일)과 유형 (line)을 시도해보십시오. 인수로 열린 파일을 사용하면 문제를 재현 할 수 없습니다! (코드에는 다른 버그가 있지만 그 예외를 일으키는 것은 없습니다). 오 BTW, 모범 사례로서 file, 당신 자신의 목적을 위해 - 그것은 엄청난 양의 혼란을 유발합니다!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top