str.find() 遇到问题

发布于 2024-07-22 04:44:30 字数 1277 浏览 4 评论 0原文

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

I'm trying to use the str.find() and it keeps raising an error, what am I doing wrong?

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))

Error

  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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一刻暧昧 2024-07-29 04:44:30

使用内置函数 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, 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

Use the built-in function open() instead of codecs.open().

You're running afoul of the difference between non-Unicode (Python 3 bytes, Python 2 str) and Unicode (Python 3 str, Python 2 unicode) string types. Python 3 won't convert automatically between non-Unicode and Unicode like Python 2 will. Using codecs.open() without an encoding parameter returns an object which yields bytes when you read from it.

Also, your countLOC function won't work:

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

That for loop will iterate over the numbers from zero to one less than the position of '#' in the string (letter = 0, 1, 2...); whitespace isn't a method of integers, and even if it were, you're not calling it.

Also, you're never incrementing LOC if the line doesn't contain #.

A "fixed" but otherwise faithful (and inefficient) version of your 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

How I might write the function:

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
乜一 2024-07-29 04:44:30

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

Are you actually passing an open file to the function? Maybe try printing type(file) and type(line), as there's something fishy here -- with an open file as the argument, I just can't reproduce your problem! (There are other bugs in your code but none that would cause that exception). Oh btw, as best practice, DON'T use names of builtins, such as file, for your own purposes -- that causes incredible amounts of confusion!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文